工具类-树形数据遍历 treeDeep
一个用于深度遍历树形节点的工具函数。传入树数据和对应的处理函数,生成新的树
interface TreeDeepOptions<T, P> {
tree: T[];
handler: (item: Readonly<T>) => P;
childrenKey?: string;
newChildrenKey?: string;
}
const treeDeep = <T, P>({
tree,
handler,
childrenKey = 'children',
newChildrenKey = childrenKey,
}: TreeDeepOptions<T, P>): P[] => {
if (!tree) return [];
return tree.map(item => {
const { [childrenKey]: children } = item as any;
const newItem = handler(item);
delete (newItem as any)[childrenKey];
(newItem as any)[newChildrenKey] = treeDeep({
tree: children,
handler,
childrenKey,
newChildrenKey,
});
return newItem;
});
};
参数说明
tree:树节点数据
handler:遍历树节点时的处理函数,函数的返回值将作为 treeDeep 函数生成的新树的节点
childrenKey:树节点的子节点字段名称, 可选参数,默认值: children
newChildrenKey:生成新树的子节点字段名称,可选参数,默认值: childrenKey
的值
返回值说明
将返回一个与传入的树数据结构一致的新树,节点为 handler
函数返回的值,使用 newChildrenKey
取代 childrenKey
作为新书子节点数据
示例
给所有树节点增加一个字段 name
, 并将树节点的 child
替换为 children
// 树数据
const treeData = [
{
id: '1',
child: [
{
id: '1-1',
child: [
{
id: '1-1-1',
},
],
},
],
},
{
id: '2',
child: [
{
id: '2-1',
},
{
id: '2-2',
},
],
},
{
id: '3',
},
];
const result = treeDeep({
tree: treeData,
handler: item => ({ ...item, name: `tree ${item.id}` }),
childrenKey: 'child',
newChildrenKey: 'children',
});
console.log(result);
打印的 result 结果:
[
{
"id": "1",
"name": "tree 1",
"children": [
{
"id": "1-1",
"name": "tree 1-1",
"children": [{ "id": "1-1-1", "name": "tree 1-1-1", "children": [] }]
}
]
},
{
"id": "2",
"name": "tree 2",
"children": [
{ "id": "2-1", "name": "tree 2-1", "children": [] },
{ "id": "2-2", "name": "tree 2-2", "children": [] }
]
},
{ "id": "3", "name": "tree 3", "children": [] }
]
原文地址:https://blog.csdn.net/z_e_n_g/article/details/143731367
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!