javascript遍历多层级数据
代码
// data:需要处理的数据 level:用于标记数据所在层级(从1开始)
const dataLoop=(data, level = 1)=>{
return data.map(item=>{
let r = {...item, level}
console.log('item', item)
// 判断如果有下级,就传入children继续向下循环
if(r.children && r.children.length){
r.children = dataLoop(r.children, level+1)
}
return r
})
}
let tree = [
{ id: '1', name: '1', children: [
{ id: '1-1', name: '1-1'},
{ id: '1-2', name: '1-2'},
{ id: '1-3', name: '1-3', children: [
{ id: '1-3-1', name: '1-3-1'},
{ id: '1-3-2', name: '1-3-2'},
{ id: '1-3-3', name: '1-3-3', children: [
{ id: '1-3-3-1', name: '1-3-3-1'},
{ id: '1-3-3-2', name: '1-3-3-2'},
{ id: '1-3-3-3', name: '1-3-3-3'},
]},
]},
]},
{ id: '2', name: '1'}
]
const result = dataLoop(tree)
console.log('result', result)
截图
-
所有层级的数据都打印了出来
-
处理后的数据