如何检查JSON对象数组中是否存在某个键?

3

我有以下的JSON对象数组:

   let data = [
       {
          "node":[
             {
                "name":"aaaaa",
                "count":"2",
             }
          ]
       },
       {
          "client":[
             {
                "name":"bbbbb",
                "count":"2",
             }
          ]
       },
       {
          "ip_address":[
             {
                "name":"ccccc",
                "count":"3",
             }
          ]
       },
       {
          "compute":[
             {
                "name":"dddd",
                "count":"1",
             }
          ]
       }
    ]

let find_key = "ip_address";

需要检查根键是否存在(例如需要查找ip_address是否存在)。请不要使用foreach

JSFiddle链接:https://jsfiddle.net/b9gxhnko/

已尝试以下方法但无效。希望能得到一些帮助。提前感谢您的帮助。 像下面这样尝试,但它不起作用(始终返回false):

    console.log(data[0].has(find_key)); // false
    console.log(data.has(find_key)); // false
    console.log(data[0].hasOwnProperty(find_key)); // false

2
这个回答解决了你的问题吗?如何在JavaScript中检查对象是否具有键? - rohaldb
他们正在使用has方法,但我需要使用_some方法。我已经得到了答案。感谢您的回复。 - kalaiyarasi M
2个回答

2
你可以尝试使用 array.some() 来解决:
let exists = data.some(x => x[find_key]);

  let data = [
       {
          "node":[
             {
                "name":"aaaaa",
                "count":"2",
             }
          ]
       },
       {
          "client":[
             {
                "name":"bbbbb",
                "count":"2",
             }
          ]
       },
       {
          "ip_address":[
             {
                "name":"ccccc",
                "count":"3",
             }
          ]
       },
       {
          "compute":[
             {
                "name":"dddd",
                "count":"1",
             }
          ]
       }
    ]

let find_key = "ip_address";

let exists = data.some(x => x[find_key]);
console.log(exists);


1
你有一个对象数组,_.has()in 期望是单个对象。现在你检查数组是否有一个名为ip_address的键,但实际上它没有。使用Array.some()或lodash的_.some(),并检查每个对象是否具有该键:

const data = [{"node":[{"name":"aaaaa","count":"2"}]},{"client":[{"name":"bbbbb","count":"2"}]},{"ip_address":[{"name":"ccccc","count":"3"}]},{"compute":[{"name":"dddd","count":"1"}]}]

// vanilla JS
const result1 = data.some(o => 'ip_address' in o)

console.log(result1)

// lodash
const result2 = _.some(data, o => _.has(o, 'ip_address'))

console.log(result1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接