树形数据,需要给每层的数据添加层级,如下:
const treeData = [
{
id: 1, name: 'a', children: [
{ id: 101, name: 'a1', children: null }
]
},
{
id: 2, name: 'b', children: [
{
id: 201, name: 'b1', children: [
{ id: 211, name: 'b2', children: null }
]
}
]
},
]
const arrayTreeAddLevel = (array, levelName = 'level', childrenName = 'children') => {
if (!Array.isArray(array)) return []
const recursive = (array, level = 0) => {
level++
return array.map(v => {
v[levelName] = level
const child = v[childrenName]
if (child && child.length) recursive(child, level)
return v
})
}
return recursive(array)
}
const newData = arrayTreeAddLevel(treeData)
标签:层级,const,name,level,js,树形,id,array,children
From: https://www.cnblogs.com/ZerlinM/p/17146863.html