从后端接口获取的数据,需要将其渲染成树形结构
获取到的数据大概如下
Data = [
{
baseMsgCaseRule: { id: 1, name: 'wj' },
childrenList: [
{
baseMsgCaseRule: { id: 1 - 1, name: 'wjj' },
childrenList: []
},
{
baseMsgCaseRule: { id: 1 - 2, name: 'wjjj' },
childrenList: []
},
{
baseMsgCaseRule: { id: 1 - 3, name: 'wjjjj' },
childrenList: []
}
]
},
{
baseMsgCaseRule: { id: 2, name: 'ck' },
childrenList: [
{
baseMsgCaseRule: { id: 2 - 1, name: 'ckk' },
childrenList: []
},
{
baseMsgCaseRule: { id: 2 - 2, name: 'ckkk' },
childrenList: []
},
{
baseMsgCaseRule: { id: 2 - 3, name: 'ckkkk' },
childrenList: []
}
]
}
]
而渲染成树形结构的数据大概如下
Data = [
{
id: 1,
name: 'wj',
childrenList: [
{
id: 1 - 1,
name: 'wjj',
childrenList: []
},
{
id: 1 - 2,
name: 'wjjj',
childrenList: []
},
{
id: 1 - 3,
name: 'wjjjj',
childrenList: []
}
]
},
{
id: 2,
name: 'ck',
childrenList: [
{
id: 2 - 1,
name: 'ckk',
childrenList: []
},
{
id: 2 - 2,
name: 'ckkk',
childrenList: []
},
{
id: 2 - 3,
name: 'ckkkk',
childrenList: []
}
]
}
]
二、解决的方法
由于笔者经验较少,思考了很久,唉~
观察获取到的数组和希望得到的数组,可以发现相似的规律,那么可以用递归去删除、添加、修改数组对象的相关属性,相关代码如下
console.log(Data)
function change(arr) {
// 遍历数组
arr.forEach((item) => {
if (item.baseMsgCaseRule) {
changeObj(item,item.baseMsgCaseRule)
// 删除该属性
delete item.baseMsgCaseRule
}
if(item.childrenList){
item.children = item.childrenList
delete item.childrenList
}
// 递归
change(item.children)
})
}
function changeObj(item,obj){
// 遍历对象
for (const key in obj) {
// 通过循环遍历给对象添加新的属性及属性值
item[key] = obj[key]
}
}
最后打印出的Data与预期一致
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)