const Person = [
{
firstname: "john",
lastname: "doe",
items: [
{
visible: true,
foo: "bar"
},
{
visible: false,
foo: "bar"
},
{
visible: true,
foo: "bar"
},
]
},
{
firstname: "jane",
lastname: "doe",
items: [
{
visible: false,
foo: "bar"
},
{
visible: true,
foo: "bar"
}
]
},
{
firstname: "john",
lastname: "adam",
items: [
{
visible: true,
foo: "bar"
},
{
visible: false,
foo: "bar"
},
{
visible: false,
foo: "bar"
}
]
},
]
在上述情况下,如何仅通过Person
或visible: true
false
个对象数组过滤items
个对象数组?
因此,一旦过滤完成,Persons
数组将仅包含Person对象,为此,每个item
对象将仅包含true
或false
对象。
任何帮助将不胜感激!谢谢!
答案 0 :(得分:0)
您可以使用Array.reduce
和Array.filter
尝试这样的事情:
const data = [{ firstname: "john", lastname: "doe", items: [{ visible: true, foo: "bar" }, { visible: false, foo: "bar" }, { visible: true, foo: "bar" }, ] }, { firstname: "jane", lastname: "doe", items: [{ visible: false, foo: "bar" }, { visible: true, foo: "bar" } ] }, { firstname: "john", lastname: "adam", items: [{ visible: true, foo: "bar" }, { visible: false, foo: "bar" }, { visible: false, foo: "bar" } ] }, ]
const filter = (arr, v) => arr.reduce((r,{firstname, lastname, items}) =>
[...r , {firstname, lastname, items: items.filter(x => x.visible == v)}], [])
console.log('visible:', filter(data, true))
console.log('not visible:', filter(data, false))