通过对象的嵌套数组布尔属性过滤对象数组

时间:2018-12-03 05:24:55

标签: javascript

const Person = [
    {
        firstname: "john",
        lastname: "doe",
        items: [
            {
                visible: true,
                foo: "bar"
            },
            {
                visible: false,
                foo: "bar"
            }
        ]
    },
        {
        firstname: "jane",
        lastname: "doe",
        items: [
            {
                visible: false,
                foo: "bar"
            }
        ]
    },
    {
        firstname: "john",
        lastname: "adam",
        items: [
            {
                visible: true,
                foo: "bar"
            },
            {
                visible: false,
                foo: "bar"
            }
        ]
    },
]

在上面的Person对象数组中,我有一个items对象数组,它们具有属性visible。我正在尝试根据Person字段visibletrue来过滤false对象。过滤后的Person对象的items数组对象也将仅包含true或false。我该如何实现?

我尝试过:

我尝试过:

const filteredPerson = Person.filter(person => {
    person.items.filter(item => item.visible === true)
})

2 个答案:

答案 0 :(得分:2)

使用Array.some

const Person = [{firstname: "john",lastname: "doe",items: [{visible: true,foo: "bar"}]},{firstname: "jane",lastname: "doe",items: [{visible: false,foo: "bar"}]},{firstname: "john",lastname: "adam",items: [{visible: true,foo: "bar"}]}];
// Filters all those objects in Person array which has atleast one visible item
const result = Person.filter(v => v.items.some(o => o.visible));
console.log(result);

编辑(使用嵌套的Array.filter)

const Person = [{firstname: "john",lastname: "doe",items: [{visible: true,foo: "bar"},{visible: false,foo: "bar"}]},{firstname: "jane",lastname: "doe",items: [{visible: false,foo: "bar"}]},{firstname: "john",lastname: "adam",items: [{visible: true,foo: "bar"},{visible: false,foo: "bar"}]}];
// Filters all those objects in Person array which has atleast one visible item
const result = Person.filter(v => {
  const filteredItems = v.items.filter(o => o.visible);
  if(filteredItems.length) { // if there is any visible item
    v.items = filteredItems;
    return true;
  }
});
console.log(result);

答案 1 :(得分:2)

这里一个filter()就足够了。由于 item 中的 visible 属性位于0索引处,因此可以使用该索引:

const Person = [{firstname: "john",lastname: "doe",items: [{visible: true,foo: "bar"}]},{firstname: "jane",lastname: "doe",items: [{visible: false,foo: "bar"}]},{firstname: "john",lastname: "adam",items: [{visible: true,foo: "bar"}]}];

const filteredPerson = Person.filter(person => person.items[0].visible)
console.log(filteredPerson);

如果未知属性索引,则必须在some()中使用filter()。您可以使用map()从数组中的对象返回特定属性:

const Person = [{firstname: "john",lastname: "doe",items: [{visible: true,foo: "bar"}]},{firstname: "jane",lastname: "doe",items: [{visible: false,foo: "bar"}]},{firstname: "john",lastname: "adam",items: [{visible: true,foo: "bar"}]}];

const filteredPerson = Person.filter(person => person.items.some(s =>s.visible)).map(p => ({items: p.items}));
console.log(filteredPerson);