实现
const flatten = (data, childKey = 'children') => {
const newArr = [];
traverItem(item => {
const {[childKey]: children, ...rest} = item;
newArr.push(rest);
})(data, childKey);
return newArr;
};
遍历树,获取节点数据。
使用
flatten(data, childKey);
- data:列表数据
- childKey:子节点属性值,默认为 `children`
示例
const data = [
{
path: "/a",
name: "a",
parentId: "",
children: [
{ path: "/a/1", name: "a1", parentId: "/a", children: [] },
{ path: "/a/3", name: "a3", parentId: "/a", children: [] },
{ path: "/a/2", name: "a2", parentId: "/a", children: [] },
],
},
{
path: "/c",
name: "c",
parentId: "",
children: [
{ path: "/c/1", name: "c1", parentId: "/c", children: [] },
{ path: "/c/2", name: "c2", parentId: "/c", children: [] },
],
},
{
path: "/b",
name: "b",
parentId: "",
children: [
{
path: "/b/1",
name: "b1",
parentId: "/b",
children: [
{ path: "/b/1/1", name: "b11", parentId: "/b/1", children: [] },
],
},
{ path: "/b/2", name: "b2", parentId: "/b", children: [] },
],
},
]
flatten(data);