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

新手上路,请多包涵

我想检查像下面这样的 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
} ]

原文由 Rawland Hustle 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 469
2 个回答

您还可以使用 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>

原文由 Andriy 发布,翻译遵循 CC BY-SA 4.0 许可协议

这将为您提供一个包含与 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);

原文由 kevin ternet 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题