如何对子元素执行操作并返回父元素?

马尔维特

我有一个这样的数组

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' },
    ] 
  }
];

使用 aflatMap并且filter仅在我需要包含子元素的父对象时才返回子元素

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

{ "name": "Child Brand 2","status": "active" }
沙丁鱼

由于您尚未发布任何代码,因此很难知道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(parent => ({
  ...parent,
  childBrands: parent.childBrands.filter(child => child.status === 'active')
}));

console.log(filtered)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

对于父元素,有两个子元素。如果子项1的.text()匹配,如何对子项2执行操作

如何根据内容(包括大于父元素)调整绝对子元素的大小?

强制使用绝对子元素以适合父元素填充

jQuery找到子元素的父元素,然后对初始父元素的另一个子元素执行操作

如何获得.first()返回的元素的父名称?

在dragstart时如何返回父元素编号

如何对组中的每个元素执行操作

在父组件中获取对子组件元素的引用

如何执行为observable返回的列表的每个元素返回单个并将其作为列表返回的操作?

如何获得元素的父元素?

如何选择元素的父元素

对列表的每个元素执行操作,返回一个 Flowable

如何使用 javascript 防止父级 onclick 对子级的操作

XSLT 对子元素排序

如何淡出父元素?

如何选择父元素?

如何获得父元素?

如何获取父元素

如何选择父元素?

CSS-如果父元素具有:: before,则对子元素进行样式设置

如何解决此父项:元素返回空?

使用先前的元素值对每个元素执行操作后,使用Java 8 Stream Reduce返回List

即使事件由其子元素触发,如何仅在父元素上执行回调?

如何在Juila中逐元素执行exp()操作?

如何对列表中元素的所有组合执行操作?

如何对动态添加的元素执行动态操作?

如何对div的span元素执行一些操作?

如何使用 indecies 在 Python 中的列表元素之间执行操作?

确定父容器子元素是否包含特定类并执行某些操作的条件