kalaiyarasi M
kalaiyarasi M

Reputation: 271

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

Upvotes: 3

Views: 2908

Answers (2)

Ori Drori
Ori Drori

Reputation: 192006

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>

Upvotes: 1

mickl
mickl

Reputation: 49955

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

Upvotes: 2

Related Questions