简体   繁体   中英

How to check if a key is exists in JSON Array of Objects

I am having the JSON array of objects like below,

   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";

Need to check whether the root key is exists or not(for example need to find ip_address is exists or not). without foreach please.

JSFiddle Link : https://jsfiddle.net/b9gxhnko/

Tried the following ways but no luck. Some help would be appreciated. Thanks in advance. Tried like below, but its not working (always returning false ),

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

You can try with 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);

You have an array of objects, and _.has() an the in expect as single object. Right now you check if the array has a key called ip_address , which it doesn't. Use Array.some() or lodash's _.some() , and check if each object has the key:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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