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?
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?
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)
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).
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