我有一个array
看起来像这样检查对象 - >关键是已经在阵列
const arr = ["a", "b", "c", {d: [...]}, {e: [...]}, "f", "g"]
我将如何检查是否object
与key
d
或e
是数组中?
我有一个array
看起来像这样检查对象 - >关键是已经在阵列
const arr = ["a", "b", "c", {d: [...]}, {e: [...]}, "f", "g"]
我将如何检查是否object
与key
d
或e
是数组中?
如果您只需要在一个级别上检查密钥,则可以使用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)
您可以使用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
方法)。
你可以使用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
阅读[这](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-一个属性,在JavaScript的)。然后,你需要做的就是循环访问数组并测试每个成员。 –