Home > OS >  Check for a key inside In array of objects
Check for a key inside In array of objects

Time:06-08

I am trying to find the best way to check whether an object key is present inside multiple objects present in an array which will provide a boolean as output [{alert:hi},{alert:bye},{}]

From the above example basically what I am trying to achieve is if any one object is missing the alert object key the output should be as false or anything

CodePudding user response:

You can iterate your array with every(). Something like this:

const objects = [{alert:'hi'},{alert:'bye'},{}];
const every = objects.every(obj => obj.hasOwnProperty('alert'));
console.log(every);

CodePudding user response:

You can use the Array#some method and check if at least one element is undefined

const isAlertMissing = (array) => array.some(elem => elem.alert === undefined)

const objs1 = [{alert: "foo"},{alert: "foo"},{}]
const objs2 = [{alert: "foo"},{alert: "foo"}]

console.log(isAlertMissing(objs1))
console.log(isAlertMissing(objs2))

CodePudding user response:

You can use every to check all items and some with Object.keys for finding a key in the inner objects.

const data = [{alert:"hi"},{alert:"bye"},{}]
const result = data.every(item => Object.keys(item).some(key => key === "alert"));

console.log(result) //false

EDIT

some with Object.keys is kind of roundabout, so we can use hasOwnProperty instead.

const data = [{alert:"hi"},{alert:"bye"},{}]
const result = data.every(item => item.hasOwnProperty("alert"));

console.log(result) //false

CodePudding user response:

Array#some will succeed as soon a match is found, making it more efficient than Array#every.

const test = (data, propName) => 
  !(data.some((el) => !el.hasOwnProperty(propName)))

const data1 = [ {alert:'hi'}, {alert:'bye'}, {}]
const data2 = [ {alert:'hi'}, {alert:'bye'}]

console.log(test(data1, 'alert')) // false
console.log(test(data2, 'alert')) // true

Or:

const test = (data, propName) => {  
  for(let el of data) {
    if(!el.hasOwnProperty(propName)) 
      return false 
  }

  return true
}

const data1 = [ {alert:'hi'}, {alert:'bye'}, {}]
const data2 = [ {alert:'hi'}, {alert:'bye'}]

console.log(test(data1, 'alert')) // false
console.log(test(data2, 'alert')) // true

  • Related