// m叉树转数组
const obj = {
id: 1,
name: "部门1",
pid: 0,
children: [
{
id: 2,
name: "部门2",
pid: 1,
children: []
},
{
id: 3,
name: "部门3",
pid: 1,
children: [
{
id: 4,
name: "部门4",
pid: 3,
children: [
{
id: 5,
name: "部门5",
pid: 4,
children: []
}
]
}
]
}
]
}
// 递归
/**
* @param {obj: object, res: array}
* @return {arr: array}
*/
function fn(obj, res = []) {
res.push(obj);
if (obj.children && obj.children.length) {
for (const item of obj.children) {
fn(item, res);
}
}
return res;
}
// 循环
function fn2(obj) {
const stack = [];
const res = [];
stack.push(obj);
while (stack.length) {
const item = stack[0];
res.push(item);
stack.shift();
if (item.children && item.children.length) {
stack.push(...item.children);
}
}
return res;
}
// 循环2//最优解
function fn3(root){
const stack = [];
const res = [];
stack.push(root);
while(stack.length){
let obj = stack.shift();
let curObj = {}
for(let key of Reflect.ownKeys(obj)){
if(key === 'children'){
for(let item of obj[key]){
stack.push(item);
}
}else{
curObj[key] = obj[key];
}
}
res.push(curObj);
}
return res;
}
console.log(fn3(obj));