假设我有一棵像下面这样的对象树,可能是使用此处找到的优秀算法创建的: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": []
}]
}]
}
(特别是在这个例子中,该函数返回的数组作为 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);
更新:
抱歉,没有注意到您需要设置parent 和level。请在下面找到新功能:
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))
);
关于javascript - 从对象树构造平面数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32609284/