js一个两层的树形数组数据列表,需要过滤出满足条件的某个孩子,且要关联出它的父级,给出例子
时间: 2024-04-30 08:19:22 浏览: 10
假设有如下的两层树形数组数据列表:
```javascript
const list = [
{
id: 1,
name: 'Parent 1',
children: [
{ id: 11, name: 'Child 11' },
{ id: 12, name: 'Child 12' },
{ id: 13, name: 'Child 13' },
],
},
{
id: 2,
name: 'Parent 2',
children: [
{ id: 21, name: 'Child 21' },
{ id: 22, name: 'Child 22' },
{ id: 23, name: 'Child 23' },
],
},
];
```
假设我们要过滤出 `id` 为 21 的孩子,并且要关联出它的父级,可以使用如下的代码:
```javascript
const targetId = 21;
const targetChild = list
.map(parent => ({
...parent,
children: parent.children.filter(child => child.id === targetId),
}))
.find(parent => parent.children.length > 0);
console.log(targetChild);
```
输出结果为:
```javascript
{
id: 2,
name: 'Parent 2',
children: [
{ id: 21, name: 'Child 21' },
],
}
```
这里使用了 `Array.prototype.map()` 方法和 `Array.prototype.find()` 方法来实现过滤和关联父级的功能。首先使用 `map()` 方法遍历每个父级,然后对每个父级的孩子进行过滤,只保留 `id` 等于目标 `id` 的孩子。过滤后,再使用 `find()` 方法找到第一个孩子不为空的父级,即为我们要找的目标孩子的父级。