繁体   English   中英

如何检查JSON数组对象是否包含密钥

[英]How to check if a JSON Array object contains a Key

{
  "myJSONArrayObject": [
    {
      "12": {}
    },
    {
      "22": {}
    }
  ]
}  

我有上面的JSON Array对象。 如何检查myJSONArrayObject是否具有特定键?

这种方法不起作用:

let myIntegerKey = 12;

if (myJSONArrayObject.hasOwnProperty(myIntegerKey))
      continue;

当它包含一个键时,它似乎返回false;而当它不包含键时,它返回true。

myJSONArrayObject是一个数组。 它没有12个属性(除非数组中有12个以上的项目)

因此,请检查数组中的some对象是否具有myIntegerKey作为属性。

const exists = data.myJSONArrayObject.some(o => myIntegerKey in o)

或者myIntegerKey始终是自己的属性

const exists = data.myJSONArrayObject.some(o => o.hasOwnProperty(myIntegerKey))

这是一个片段:

 const data={myJSONArrayObject:[{"12":{}},{"22":{}}]}, myIntegerKey = 12, exists = data.myJSONArrayObject.some(o => myIntegerKey in o); console.log(exists) 

"myJSONArrayObject"是一个数组,因此您必须检查其每个元素上的hasOwnProperty

let myIntegerKey = 12;

for (var obj in myJSONArrayObject) {
  console.log(obj.hasOwnProperty(myIntegerKey));
}

 const obj = { myJSONArrayObject: [ { 12: {}, }, { 22: {}, }, ], }; const myIntegerKey = '12'; const isExist = obj.myJSONArrayObject.findIndex((f) => { return f[myIntegerKey]; }) > -1; console.log(isExist); 

您可以使用every()使其更快

 const obj = { myJSONArrayObject: [ { 22: {}, }, { 12: {}, }, ], }; const myIntegerKey = '12'; const isExist = !obj.myJSONArrayObject .every((f) => { return !f[myIntegerKey]; }); console.log(isExist); 

注意 :此处的键名( 12: {}, )不依赖于typeof myIntegerKey12'12'都将返回true

通过键检索对象的最直接方法是使用JavaScript括号表示法 同样,也可以使用find方法遍历数组。

 const obj = { myJSONArrayObject: [{ 12: {}, }, { 22: {}, }, ], }; const myIntegerKey = 12; const myObject = obj.myJSONArrayObject.find(item => item[myIntegerKey]); console.log("exists", myObject !== undefined); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM