如何检查array Javascript中是否存在对象数组键



我有以下数组

let newArray = [
{
"conterTop": {
"uncategroized": [item1, item2, item3],
"categroized": [item4, item5]
}
},
{
"flooring": {
"uncategroized": [item1, item2, item3],
"categroized": [item4, item5]
}
}
]

我在推台面&地板在运行时。现在我需要检查newArray中是否已经存在台面,它不应该再次推动台面。我尝试过newArray.includes((,但它不起作用。有什么建议吗?

您可以过滤数组以查找匹配的关键字,并检查过滤数组的长度。如果长度大于0,则它存在。如果没有,就没有。

newArray.filter(x => return typeof(x.countertop) !== "undefined").length > 0

这里我刚刚过滤掉了每个没有counterTop的值,并检查是否有任何值离开

let newArray = [{
"conterTop": {
"uncategroized": [1, 2, 3],
"categroized": [4, 5]
}
},
{
"flooring": {
"uncategroized": [1, 2, 3],
"categroized": [4, 5]
}
}
];
let isCounterTopExists = newArray.filter(x => x.conterTop).length > 0
console.log(isCounterTopExists);

这就是Array.prototype.some的用途:

let newArray = [
{
"conterTop": {}
},
{
"flooring": {}
}
];
let testArray = [
{
"flooring": {}
}
];
const testArrayResult = testArray.some(obj => obj.conterTop);
const newArrayResult = newArray.some(obj => obj.conterTop);
console.log("testArray has 'conterTop':", testArrayResult);
console.log("newArray has 'conterTop':", newArrayResult);

最新更新