0

I have an array looking like this

const arr = ["a", "b", "c", {d: [...]}, {e: [...]}, "f", "g"]

How would I check if the object with the key d or e is in the array?

four-eyes
  • 10,740
  • 29
  • 111
  • 220
  • Read [this](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript). Then all you need to do is loop through the array and test each member. – Matt Burland Aug 10 '17 at 16:39

3 Answers3

1

You can use some() if you only need to check for key on one level.

const arr = ["a", "b", "c", {d: [1]}, {e: [1]}, "f", "g"]

var check = arr.some(function(e) {
  return typeof e == 'object' && (e.hasOwnProperty('d') || e.hasOwnProperty('e'))
})

console.log(check)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

You can use ES2015's Object.keys() to get object's own enumerable keys:

const hasMatchingObject = arr.some((element) => {
    return (
        element instanceof Object &&
        (
            Object.keys(element).includes("d") ||
            Object.keys(element).includes("e")
        )
    );
});

(notice that I've used includes which is part of ES2016, but you could also use the old indexOf method).

mdziekon
  • 3,531
  • 3
  • 22
  • 32
0

You could use find with arrow function:

const arr = ["a", "b", "c", {d: [{id:1, value:'value d'}]}, 
                {e: [{id:1, value:'value e'}]}, "f", "g"];  

console.log(arr.find(i => i.d)); // will return the object/array
console.log(arr.find(i => i.x)); // undefined, it doesn't exist
HienaKill
  • 101
  • 2
  • 10