检查对象 - > key已经在数组中

时间:2017-08-10 16:35:20

标签: javascript arrays object

我有array看起来像这样

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

如何检查带有object keyd的{​​{1}}是否在数组中?

3 个答案:

答案 0 :(得分:1)

如果您只需要在一个级别检查密钥,则可以使用some()

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)

答案 1 :(得分:0)

您可以使用ES2015的Object.keys()来获取对象自己的可枚举密钥:

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

(请注意,我已使用includes作为ES2016的一部分,但您也可以使用旧的indexOf方法。

答案 2 :(得分:0)

您可以find使用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
相关问题