js的tree数组对象扁平化思否_JS中树形对象与数组之间的相互转换

const treeObj ={

id:'0',

name:'0',

children:[

{

id:'1',

name:'anc',

children:[

{

id:'1-1',

name:'anc',

children:[

{

id:'1-1-1',

name:'anc',

},

{

id:'1-1-2',

name:'anc'},

]

},

{

id:'1-2',

name:'anc',

children:[

{

id:'1-2-1',

name:'anc',

},

{

id:'1-2-2',

name:'anc'},

]

},

]

},

{

id:'2',

name:'anc',

children:[

{

id:'2-1',

name:'anc',

children:[

{

id:'2-1-1',

name:'anc',

},

{

id:'2-1-2',

name:'anc'},

]

},

{

id:'2-2',

name:'anc',

children:[

{

id:'2-2-1',

name:'anc',

children: [

{

id:'2-2-1-1',

name:'anc',

},

{

id:'2-2-1-2',

name:'anc'},

]

},

{

id:'2-2-2',

name:'anc'},

]

},

{

id:'2-3',

name:'anc',

children:[

{

id:'2-3-1',

name:'anc',

},

{

id:'2-3-2',

name:'anc'},

]

},

]

},

{

id:'3',

name:'anc',

children:[]

}

]

};//将treeObj中的所有对象,放入一个数组中,要求某个对象在另一个对象的children时,其parent_id是对应的另一个对象的id//其原理实际上是数据结构中的广度优先遍历

functiontree2Array(treeObj, rootid) {

const temp= []; //设置临时数组,用来存放队列

const out = []; //设置输出数组,用来存放要输出的一维数组

temp.push(treeObj);//首先把根元素存放入out中

let pid =rootid;

const obj=deepCopy(treeObj);

obj.pid=pid;delete obj['children'];

out.push(obj)//对树对象进行广度优先的遍历

while(temp.length > 0) {

const first=temp.shift();

const children=first.children;if(children && children.length > 0) {

pid=first.id;

const len=first.children.length;for(let i=0;i

temp.push(children[i]);

const obj=deepCopy(children[i]);

obj.pid=pid;delete obj['children'];

out.push(obj)

}

}

}returnout

}

console.log(tree2Array(treeObj,'root'))//深拷贝

functiondeepCopy(obj){//深度复制数组

if(Object.prototype.toString.call(obj) === "[object Array]"){

const object=[];for(let i=0;i

object.push(deepCopy(obj[i]))

}returnobject

}//深度复制对象

if(Object.prototype.toString.call(obj) === "[object Object]"){

const object={};for(let p inobj){

object[p]=obj[p]

}returnobject

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值