通过子对象的属性过滤对象的父子数组

时间:2018-12-03 07:21:32

标签: javascript

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"
            }
        ]
    },
]

在上述情况下,如何仅通过Personvisible: true false个对象数组过滤items个对象数组?

因此,一旦过滤完成,Persons数组将仅包含Person对象,为此,每个item对象将仅包含truefalse对象。

任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用Array.reduceArray.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))