【问题标题】:Underscore.js: filter objects with nested array of objsUnderscore.js:使用嵌套的 objs 数组过滤对象
【发布时间】:2021-06-10 15:55:29
【问题描述】:

我正在尝试根据嵌套数据过滤顶级对象(嵌套对象也需要过滤)。

过滤参数:所有具有 categoryValue A 的记录。

  const table = [
    {
      name: 'Bob',
      detail: [
        { category: 'Employeer', categoryValue: 'A' },
        { category: 'Employeer', categoryValue: 'B' },
      ],
    },
    {
      name: 'Alice',
      detail: [
        { category: 'Employeer', categoryValue: 'C' },
        { category: 'Employeer', categoryValue: 'D' },
      ],
    },
  ];

我期待以下结果

  const fileredTable = [

    { 
      //this
      name: 'Bob',
      detail: [
        //and only this
        { category: 'Employeer', categoryValue: 'A' }

      ],
    }
  ];

【问题讨论】:

    标签: javascript filter lodash


    【解决方案1】:

    好的,经过几次尝试我找到了这个解决方案:

    const filteredTable = table.flatMap((item) => {
      const filteredDetail = item.detail.filter((e) => e.categoryValue === 'A')
      return filteredDetail.length !== 0 ? {...item, detail: filteredDetail} :  []
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多