我有一个对象数组,其中一些键包含一个新数组。
现在我想返回具有特定值或属性内的嵌套数组包含特定值的所有对象。
数组看起来像是……。像这样:
const test = [
{
test: 1,
key: [{
yes: true,
no: null
}]
},
{
test: null,
key: [{
yes: true,
no: null
}]
},
{
test: null,
key: [{
yes: null,
no: null
}]
}];
我想出的解决方案,不幸的是不起作用:
const Filtered = test.filter(obj => obj.test || obj.key.filter(item => item.yes));
所以实际上,只应返回前两个对象,但它返回全部三个。
我在这里缺少什么?
最佳答案
你差点就把它带回家了。使用 obj.key.some 或 obj.filter().length > 0
Array.prototype.filter
将始终返回一个数组。当没有与谓词匹配的项时,它将为空 (.length === 0
)。
const test = [{
test: 1,
key: [{
yes: true,
no: null
}]
},
{
test: null,
key: [{
yes: true,
no: null
}]
},
{
test: null,
key: [{
yes: null,
no: null
}]
}
];
const filtered = test.filter(obj => obj.test || obj.key.filter(item => item.yes).length > 0)
console.log(filtered)
更“正确的方法”和“更高效的方法”是使用 Array.prototype.some ,因为它会在第一个“匹配”时在内部退出循环,而 filter
将循环遍历数组中的每个元素。
const predicate = obj => obj.test || obj.key.some(item => item.yes)
const filteres = test.filter(predicate)
关于javascript - 通过嵌套数组进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53005949/