【问题标题】:How do i perform an operation on a child element and return the parent?如何对子元素执行操作并返回父元素?
【发布时间】:2022-06-18 00:00:12
【问题描述】:

我有一个这样的数组

const array = [
  { 
    name: 'Parent Brand 1', 
    childBrands: [
      { name: 'Child Brand 1', status: 'active' },
      { name: 'Child Brand 2', status: 'discontinued' },
    ] 
  }
, { 
    name: 'Parent Brand 2',
    childBrands: [
      { name: 'Child Brand 1', status: 'discontinued' },
      { name: 'Child Brand 2', status: 'active' },
    ] 
  }
];

如何使它按状态过滤子品牌并返回父对象?按“活动”状态过滤后,它应该返回类似这样的内容,

const array = [
  { 
    name: 'Parent Brand 1', 
    childBrands: [
      { name: 'Child Brand 1', status: 'active' },
    ] 
  }
, { 
    name: 'Parent Brand 2',
    childBrands: [
      { name: 'Child Brand 2', status: 'active' },
    ] 
  }
];

当我需要包含子元素的父对象时,使用flatMapfilter 只返回子元素

{ "name": "Child Brand 1","status": "active" }

{ "name": "Child Brand 2","status": "active" }

【问题讨论】:

    标签: javascript arrays filter flatmap


    【解决方案1】:

    由于您尚未发布任何代码,因此很难知道在这种情况下您将如何使用flatMap()。您可以简单地map() 覆盖数组并过滤每个嵌套数组属性。

    const array = [
      {
        name: 'Parent Brand 1',
        childBrands: [
          { name: 'Child Brand 1', status: 'active' },
          { name: 'Child Brand 2', status: 'discontinued' },
        ]
      }
      , {
        name: 'Parent Brand 2',
        childBrands: [
          { name: 'Child Brand 1', status: 'discontinued' },
          { name: 'Child Brand 2', status: 'active' },
        ]
      }
    ];
    
    const filtered = array.map(o => ({ ...o, childBrands: o.childBrands.filter(b => b.status === 'active') }))
    
    console.log(filtered)

    【讨论】:

      猜你喜欢
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多