Filter array in array and get only the filtered items

a 夏天 提交于 2021-02-19 05:35:11

问题


I have the following array named filters and try to filter it by selected items.
At the end I want to have all filters where a selected item is, but only with the selected items

let filters = [
  {
    id: 0,
    name: 'property',
    items: [
      {
        id: 0,
        name: 'x',
        isSelected: false
      },
      {
        id: 1,
        name: 'y',
        isSelected: true
      }
    ]
  },
  {
    id: 1,
    name: 'property2',
    items: [
      {
        id: 0,
        name: 'x',
        isSelected: true
      },
      {
        id: 1,
        name: 'y',
        isSelected: false
      }
    ]
  }
]

I want to get the following array at the end:

let filteredFilters = [
  {
    id: 0,
    name: 'property',
    items: [
      {
        id: 1,
        name: 'y',
        isSelected: true
      }
    ]
  },
  {
    id: 1,
    name: 'property2',
    items: [
      {
        id: 0,
        name: 'x',
        isSelected: true
      }
    ]
  }
]

I tried the following code, but it does not work.

let filteredFilters = filters.filter(filter => {
    return filter.items.filter(item => {
       return item.isSelected === true;
  })
})

回答1:


You need map + filter since you're dealing with a nested array:

let filters = [
  {
    id: 0,
    name: 'property',
    items: [
      {
        id: 0,
        name: 'x',
        isSelected: false
      },
      {
        id: 1,
        name: 'y',
        isSelected: true
      }
    ]
  },
  {
    id: 1,
    name: 'property2',
    items: [
      {
        id: 0,
        name: 'x',
        isSelected: true
      },
      {
        id: 1,
        name: 'y',
        isSelected: false
      }
    ]
  }
]


let filteredFilters = 
    filters.map(
        ({items, ...rest}) => ({...rest, items: items.filter(item => item.isSelected)})
    )
    .filter(x => x.items.length > 0);

console.log(filteredFilters);


来源:https://stackoverflow.com/questions/62056650/filter-array-in-array-and-get-only-the-filtered-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!