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

推荐答案

you can also use Array.some() function:

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>

Json相关问答推荐

Vega-Lite:文本笔画在外部

JSON字符串处理注入引号

将嵌套的json中的字符串强制转换为数字

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

如何用JQ更改空/布尔/数字的 colored颜色 ?

使用JQ合并JSON列表中的对象

用 Jolt 替换 JSON 中的值

jq:将一个数组与多个数组连接起来

在 VS Code 中将一个正则表达式替换为另一个正则表达式

条件性构建/修改嵌套对象数组

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

用于遮蔽卡的 Jolt 规格

判断 JSON 中的对象,而不是条件中提到的对象

JBuilder中未定义的局部变量或方法json

从 Postgres 中的 json 对象中提取键、值

ASP.NET MVC:使用 JsonResult 控制属性名称的序列化

json_encode() 返回 false

使用 application/json 优于 text/plain 的优势?

你如何在 Arrays of Arrays 上 OPENJSON

从调试器获取 IntelliJ Idea 中的 JSON 对象