js遍历树结构并为每个节点设置一个属性为层级?

// 请问怎么在每一层加一个当前层级的属性

[

{

"name": "一号",

"code": "00001",

"children": [

{

"name": "231231132123132",

"code": "12122121231231",

"children": []

},

{

"name": "啊阿斯顿",

"code": "111导电",

"children": []

},

{

"name": "ssadasd",

"code": "1113456",

"children": []

}

]

}

]


回答:

function addLevel(list, parentLevel = 0) {

return list.map(item => {

return {

...item,

level: parentLevel + 1,

children: addLevel(item.children || [], parentLevel + 1)

}

})

}

以上是 js遍历树结构并为每个节点设置一个属性为层级? 的全部内容, 来源链接: utcz.com/p/933364.html

回到顶部