如何在子元素上执行操作并退还父母?
我有这样的数组,
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' },
]
}
];
使用flatmap
和filter
仅在需要父对象(包括子元素)的父对象时返回子元素
{ "name": "Child Brand 1","status": "active" }
{ "name": "Child Brand 2","status": "active" }
I have an array like this
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' },
]
}
];
How do I make it so that it filters the child brands by status and returns the parent object? After filtering by 'active' status it should return something like this,
const array = [
{
name: 'Parent Brand 1',
childBrands: [
{ name: 'Child Brand 1', status: 'active' },
]
}
, {
name: 'Parent Brand 2',
childBrands: [
{ name: 'Child Brand 2', status: 'active' },
]
}
];
Using a flatMap
and filter
only returns the child elements when i need the parent object including the child element
{ "name": "Child Brand 1","status": "active" }
{ "name": "Child Brand 2","status": "active" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您没有发布任何代码,因此在这种情况下,很难知道如何使用
flatmap()
。您可以简单地map()
在数组上并过滤每个嵌套数组属性。Since you haven't posted any code it's hard to know how you would be using
flatMap()
in this case. You can simplymap()
over the array and filter each nested array property.您在主要数组上使用
数组#映射
,而Array#filter
在次要数组上如下:You use
Array#map
on the major array andArray#filter
on the minor arrays as follows: