By Noxxxx from https://interview.noxxxx.com/?post_type=post&p=106 上山打老虎
欢迎分享与聚合,尊重版权,可以联系授权
const destruct = (tree, id, pid, children) => {
const flatten = (node) => {
const result = [];
const queue = [node];
while(queue.length) {
const item = queue.shift();
if (item[children] && item[children].length > 0) {
item[children].forEach(c => {
queue.push({
...c,
[pid]: item[id]
})
})
}
delete item[children]
result.push(item)
}
return result;
}
// 如果是数组而非单个根节点
if (Array.isArray(tree)) {
return tree.map(item => flatten(item)).reduce((pre, cur) => pre.concat(cur), [])
} else {
return flatten(tree)
}
}
See the Pen JS 编程题 – 树转成数组 by hjoker (@hjoker) on CodePen.