我有一个像这样的简单数组:
const test = [{
test: 1,
key: [{
yes: true,
no: null
},{
yes: true,
no: null
},{
yes: false,
no: null
}]
},
{
test: true,
key: [{
yes: true,
no: null
}]
},
{
test: null,
key: [{
yes: null,
no: null
}]
}
];
我想返回一个数组,它只包含 test
为真(例如 1)的项。 test
中的 key
数组将只包含具有 key.yes
真值的对象。
所以预期的输出是:
[
{
test: 1,
key: [{yes: true, no: null},{yes: true, no: null}]
},
{
test: true,
key: [{yes: true, no: null}]
}
];
我试图通过使用像这样的简单过滤器来实现这一点:
const filtered = test.filter(obj => obj.test && obj.key.filter(item => item.yes).length > 0)
但这也会返回 key
数组的值,这些值是 false
。
有什么想法吗?
最佳答案
你需要得到一个新的外部数组和新的内部数组,因为外部过滤不会改变内部数组。如果改变内部数组并过滤外部数组,则会改变给定的数据。
要获得独立的结果,您可以检查 test
和 if truthy 过滤器 key
并为结果集获取一个新对象。
var test = [{ test: 1, key: [{ yes: true, no: null }, { yes: true, no: null }, { yes: false, no: null }] }, { test: true, key: [{ yes: true, no: null }] }, { test: null, key: [{ yes: null, no: null }] }],
result = test.reduce((r, { test, key }) => {
if (test) {
r.push({ test, key: key.filter(({ yes }) => yes) });
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 过滤特定值的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083804/