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

时间:2016-11-05 13:34:58

标签: javascript json object key

我想检查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 
} ]

4 个答案:

答案 0 :(得分:23)

您还可以使用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)));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

这将为您提供一个元素与名称匹配的数组===“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);

答案 3 :(得分:1)

使用hasOwnProperty()

简单循环遍历数组中的所有对象
var json = [...];
var wantedKey = ''; // your key here
var wantedVal = ''; // your value here

for(var i = 0; i < json.length; i++){

   if(json[i].hasOwnProperty(wantedKey) && json[i][wantedKey] === wantedVal) {
     // it happened.
     break;
   }

}