Home > Net >  Check if a Key exists in array of Objects
Check if a Key exists in array of Objects

Time:10-15

I have an array of Objects:

{
    "groceries": [{
        "fruit": "orange"
    }, {
        "fruit": "apple"
    }, {
        "vegetable": "carrot"
    }]
}

I want to check if this array has a key called vegetable. If so, return true else return false using JavaScript

groceries.find(function(ele) {
          return (Object.keys(ele).indexOf('vegetable') !== -1);
        });

Not sure if there is an efficient way to do this.

CodePudding user response:

Use in

const object = {
    "groceries": [{
        "fruit": "orange"
    }, {
        "fruit": "apple"
    }, {
        "vegetable": "carrot"
    }]
}

console.log(object.groceries.some(item => 'vegetable' in item))

CodePudding user response:

If you want to return true or false, you should use some and not find. And you can avoid checking the keys by using hasOwnProperty or hasOwn.

var data = {
    "groceries": [{
        "fruit": "orange"
    }, {
        "fruit": "apple"
    }, {
        "vegetable": "carrot"
    }]
}

const result = data.groceries.some(o => o.hasOwnProperty('vegetable'))
console.log(result);

const result2 = data.groceries.some(o => Object.hasOwn(o, 'vegetable'))
console.log(result2);

 

CodePudding user response:

When you do

Object.keys(e)

You will obtain an array, may be you have to do only this ?

Object.keys(e)[0]

Because you have only one element. And adapt it if you change your array afterwards... So your code becomes :

groceries.find(e => {
    return (Object.keys(e)[0] === 'vegetable')
});
  • Related