通过递归获取节点层级及本身信息,将树同级节点放入同一个数组

tableData: [

{

docname: "1",

doccode:'a',

id:1,

num:6,

children: [

{

docname:'1-1',

doccode:'b',

num:3,

fid:1,

id:2,

children: [

{

id:3,

fid:2,

docname:'1-1-1',

doccode:'b1',

},

{

id:4,

fid:2,

docname:'1-1-2',

doccode:'b2',

},

{

id:5,

fid:2,

docname:'1-1-3',

doccode:'b3',

}

]

},

{

docname:'1-2',

doccode:'c',

num:3,

children: [

{

docname:'1-2-1',

doccode:'c1',

},

{

docname:'1-2-2',

doccode:'c2',

},

{

docname:'1-2-3',

doccode:'c3',

}

]

}

]

}

],

怎么讲上述树形结构数据通过递归改为:
[
[

  [1],

[1-1, 1-2, ...],

[1-1-1, 1-1-2, ...],

[1-1-1-1, 1-1-1-2, ...],

],
[

  [2],

[2-1,2-2,...]

....

]
]


回答:

通过递归获取节点层级及本身信息,将树同级节点放入同一个数组

let tableData =[

{

docname: "1",

doccode:'a',

id:1,

num:6,

children: [

{

docname:'1-1',

doccode:'b',

num:3,

fid:1,

id:2,

children: [

{

id:3,

fid:2,

docname:'1-1-1',

doccode:'b1',

},

{

id:4,

fid:2,

docname:'1-1-2',

doccode:'b2',

},

{

id:5,

fid:2,

docname:'1-1-3',

doccode:'b3',

}

]

},

{

docname:'1-2',

doccode:'c',

num:3,

children: [

{

docname:'1-2-1',

doccode:'c1',

},

{

docname:'1-2-2',

doccode:'c2',

},

{

docname:'1-2-3',

doccode:'c3',

}

]

}

]

}

];

let getFieldVals=(list=[],key='',res=[])=>(res.push(list.map(item=>(item.children && getFieldVals(item.children,key,res),item[key]))),res);

getFieldVals(tableData,'docname').reverse();

0: ['1']

1: (2) ['1-1', '1-2']

2: (3) ['1-2-1', '1-2-2', '1-2-3']

3: (3) ['1-1-1', '1-1-2', '1-1-3']

以上是 通过递归获取节点层级及本身信息,将树同级节点放入同一个数组 的全部内容, 来源链接: utcz.com/p/936175.html

回到顶部