使用Javascript检查JSON对象是否包含值

Raw*_*tle 15 javascript json key object

我想检查JSON对象中的某个键是否包含某个值.假设我想检查任何对象中的键"name"是否具有值"Blofeld"(这是真的).我怎样才能做到这一点?

[ {
  "id" : 19,
  "cost" : 400,
  "name" : "Arkansas",
  "height" : 198,
  "weight" : 35 
}, {
  "id" : 21,
  "cost" : 250,
  "name" : "Blofeld",
  "height" : 216,
  "weight" : 54 
}, {
  "id" : 38,
  "cost" : 450,
  "name" : "Gollum",
  "height" : 147,
  "weight" : 22 
} ]
Run Code Online (Sandbox Code Playgroud)

And*_*riy 29

你也可以使用Array.some()功能:

const arr = [{
  id: 19,
  cost: 400,
  name: "Arkansas",
  height: 198,
  weight: 35 
}, {
  id: 21,
  cost: 250,
  name: "Blofeld",
  height: 216,
  weight: 54 
}, {
  id: 38,
  cost: 450,
  name: "Gollum",
  height: 147,
  weight: 22 
}];

console.log(arr.some(item => item.name === 'Blofeld'));
console.log(arr.some(item => item.name === 'Blofeld2'));

// search for object using lodash
const objToFind1 = {
  id: 21,
  cost: 250,
  name: "Blofeld",
  height: 216,
  weight: 54 
};
const objToFind2 = {
  id: 211,
  cost: 250,
  name: "Blofeld",
  height: 216,
  weight: 54 
};
console.log(arr.some(item => _.isEqual(item, objToFind1)));
console.log(arr.some(item => _.isEqual(item, objToFind2)));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 我认为 `filter` 和 `some` 方法的速度大致相同,都必须为每次迭代执行一个函数,但是,'some' 方法将在其函数第一次返回 true 时停止迭代。`filter` 方法将迭代整个数组。因此,如果我需要布尔值答案是否至少有一个数组项满足给定条件,我会使用 `some`,如果我需要从给定数组中检索子集数组,我会使用 `filter`。 (2认同)

kev*_*net 11

这将为您提供一个元素与 name === "Blofeld" 匹配的数组:

var data = [ {
  "id" : 19,
  "cost" : 400,
  "name" : "Arkansas",
  "height" : 198,
  "weight" : 35
}, {
  "id" : 21,
  "cost" : 250,
  "name" : "Blofeld",
  "height" : 216,
  "weight" : 54
}, {
  "id" : 38,
  "cost" : 450,
  "name" : "Gollum",
  "height" : 147,
  "weight" : 22
} ];

var result = data.filter(x => x.name === "Blofeld");
console.log(result);
Run Code Online (Sandbox Code Playgroud)


cal*_*-me 6

编写一个简单的函数来检查对象数组是否包含特定值。

var arr=[{
   "name" : "Blofeld",
   "weight" : 54 
},{
   "name" : "",
   "weight" : 22 
}];

function contains(arr, key, val) {
    for (var i = 0; i < arr.length; i++) {
        if(arr[i][key] === val) return true;
    }
    return false;
}

console.log(contains(arr, "name", "Blofeld")); //true
console.log(contains(arr, "weight", 22));//true

console.log(contains(arr, "weight", "22"));//false (or true if you change === to ==)
console.log(contains(arr, "name", "Me")); //false
Run Code Online (Sandbox Code Playgroud)