ES6 递归遍历树形结构并提取相同 type 值的节点
假设树形结构的数据如下:
const data = [
{
name: 'A',
type: 'parent',
children: [
{
name: 'B1',
type: 'child'
},
{
name: 'B2',
type: 'child'
}
]
},
{
name: 'C',
type: 'parent',
children: [
{
name: 'D1',
type: 'child'
},
{
name: 'D2',
type: 'child'
},
{
name: 'E1',
type: 'child'
}
]
}
];
我们可以使用递归的方式来将相同 type 值的对象放到一个数组里面:
const getTypeArray = (data, type) => {
let result = [];
data.forEach(item => {
if (item.type === type) {
result.push(item);
}
if (item.children && item.children.length > 0) {
result = result.concat(getTypeArray(item.children, type));
}
});
return result;
}
const parentArray = getTypeArray(data, 'parent');
const childArray = getTypeArray(data, 'child');
console.log(parentArray); // [{name: 'A', type: 'parent', children: [{name: 'B1', type: 'child'}, {name: 'B2', type: 'child'}]}, {name: 'C', type: 'parent', children: [{name: 'D1', type: 'child'}, {name: 'D2', type: 'child'}, {name: 'E1', type: 'child'}]}]
console.log(childArray); // [{name: 'B1', type: 'child'}, {name: 'B2', type: 'child'}, {name: 'D1', type: 'child'}, {name: 'D2', type: 'child'}, {name: 'E1', type: 'child'}]
在上面的代码中,我们定义了一个 getTypeArray 函数,它接受两个参数:data 和 type。其中 data 是树形结构的数据,type 是我们要查找的 type 值。我们首先定义一个空数组 result,用于存放查找结果。然后我们遍历 data 数组,如果当前元素的 type 值与参数 type 相等,就将当前元素 push 到 result 数组中。接着,我们判断当前元素是否有 children 属性,如果有,就递归调用 getTypeArray 函数,将返回的结果与 result 数组合并。最后,我们返回 result 数组作为结果。
我们可以调用 getTypeArray 函数两次,分别传入 'parent' 和 'child' 作为参数,得到 parentArray 和 childArray 两个数组,它们分别包含了所有 type 值为 'parent' 和 'child' 的元素。
原文地址: https://www.cveoy.top/t/topic/oOsr 著作权归作者所有。请勿转载和采集!