前端重组数据结构的常见几种模式与解决方案
数据格式一:
list = [{id: '01', name: '01',parent: null},
{id: '0101',name: '0101',parent: '01'},
{id: '010101',name: '010101',parent: '0101'},
{id: '0102',name: '01012',parent: '01'},
{id: '012',name: '012',parent: null},
{id: '0201',name: '0201',parent: '02'},
]
需求数组重组后输出的格式如下:
[{id::'',name:'',parent:'',children:[{id::'',name:'',parent:'',children:[{...}]}...]}]
解决方案与思路
循环递归判断
处理方式代码
const makeList = (list, parent) => {
let _new = list.filter(val => val.parent === parent)
// 排序
_new.sort((a, b) => b.name - a.name)
// 重组数据结构
for (let item of _new) {
let hasChild = list.findIndex(oo => oo.parent === item.id)
if (hasChild > -1)
item.children = makeList(list, item.id)
}
return _new
}
let newList = makeList(list, null)
console.log(newList)
数据格式二
const list = [
{ id:'01', name:'01',children:[{id:'0101',name:'0101',children:[{id:'010101',name:'010101'}]}] },
{ id:'02', name:'02',children:[{id:'0202',name:'0202',children:[{id:'020202',name:'020202'}]}] },
.................
]
需求如下:
对于这种数据结构,需要层次递进查找一个元素,或者修改其中一个元素
解决方案
const getItem = (key: string, data: {}[]) => {
data.forEach((it: any) => {
if (it.key === key) {
item = it
return
}
else if (it.children) {
getItem(key, it.children)
}
})
return item
}