The*_*per 8 javascript arrays algorithm tree hierarchy
假设我有一个像下面这样的对象树,可能是使用这里找到的优秀算法创建的:https : //stackoverflow.com/a/22367819/3123195
{
"children": [{
"id": 1,
"title": "home",
"parent": null,
"children": []
}, {
"id": 2,
"title": "about",
"parent": null,
"children": [{
"id": 3,
"title": "team",
"parent": 2,
"children": []
}, {
"id": 4,
"title": "company",
"parent": 2,
"children": []
}]
}]
}
Run Code Online (Sandbox Code Playgroud)
(特别是在这个例子中,该函数返回的数组作为children
数组属性嵌套在一个空对象中。)
我如何将它转换回平面阵列?
希望你熟悉es6:
let flatten = (children, extractChildren) => Array.prototype.concat.apply(
children,
children.map(x => flatten(extractChildren(x) || [], extractChildren))
);
let extractChildren = x => x.children;
let flat = flatten(extractChildren(treeStructure), extractChildren)
.map(x => delete x.children && x);
Run Code Online (Sandbox Code Playgroud)
更新:
抱歉,没有注意到您需要设置父级和级别。请在下面找到新功能:
let flatten = (children, getChildren, level, parent) => Array.prototype.concat.apply(
children.map(x => ({ ...x, level: level || 1, parent: parent || null })),
children.map(x => flatten(getChildren(x) || [], getChildren, (level || 1) + 1, x.id))
);
Run Code Online (Sandbox Code Playgroud)
https://jsbin.com/socono/edit?js,console
由于新答案再次提出了这个问题,因此值得考虑一种现代的简单方法:
const flatten = ({children}) =>
children .flatMap (({children = [], ...rest}) => [rest, ...flatten ({children})])
let tree = {children: [{id: 1, title: "home", parent: null, children: []}, {id: 2, title: "about", parent: null, children: [{id: 3, title: "team", parent: 2, children: []}, {id: 4, title: "company", parent: 2, children: []}]}]}
console .log (flatten (tree))
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {max-height: 100% !important; top: 0}
Run Code Online (Sandbox Code Playgroud)
使用Array.prototype.flatMap
,我们将项目映射到平面数组中,并在其children
属性上重复出现。