树状结构转数组方法
// key代表子节点的对象名
function treeTransArray(tree, key) {
return tree.reduce(function (con, item) {
var callee = arguments.callee;
con.push(item);
if (item[key] && item[key].length > 0){
item[key].reduce(callee, con);
}
return con;
}, []).map(function (item) {
item[key] = [];
return item;
})
}
声明树状对象
let obj = [{
id:'1',
name:'顶级父组件',
parentKey:'0',
children:[{
id:'1-1',
name:'第1层第1个子组件',
parentKey:'1',
children:[{
id:'1-1-1',
name:'第2层第1个子组件',
parentKey:'1-1',
children:[],
},{
id:'1-1-2',
name:'第1层第2个子组件',
parentKey:'1-1',
children:[],
},{
id:'1-1-3',
name:'第1层第3个子组件',
parentKey:'1-1',
children:[],
}]
},{
id:'1-2',
name:'第1层第2个子组件',
parentKey:'1-1',
children:[],
}],
}];
var arr = treeTransArray(obj,'children'); //输出转换后数组
console.log(arr)
网友评论