0

For eg.

[
    {
      x:1,
      y:2
     },
     {
       x:10,
       y:20
     },
]

How can I check if x exists in both of the objects inside the array?

DESIRED OUTPUT:

if x doesn't exist in even one object inside the array ---> false
else ---->true

I have tried using the array.prototype.find() method but not able to find the right logic to get the desired output.

Vikrant Bhat
  • 2,117
  • 2
  • 14
  • 32

2 Answers2

6

You could check the objects with Object.hasOwnProperty and the wanted property and take Array#every for checking all elements of the array.

var array = [{ x: 1, y: 2 }, { x: 10, y: 20 }],
    result = array.every(o => o.hasOwnProperty('x'));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use the operator in for checking if a property exists in the object, this along with the function every.

let arr = [{x:1,y:2},{x:10,y:20}];
console.log(arr.every((o) => "x" in o))
console.log(arr.every((o) => "z" in o))
Ele
  • 33,468
  • 7
  • 37
  • 75