平时我们用ajax 拿到的数据一般都是一维数组,但是我们想要渲染element树结构的时候就需要转化格式了
思路
我们要判断默认一级父元素,找到一级父元素,在递归匹配子元素
上代码
let jsonData = [{
"id": "1",
"pid": "0",
"name": "家用电器"
}, {
"id": "4",
"pid": "1",
"name": "大家电"
}, {
"id": "5",
"pid": "1",
"name": "生活电器"
}, {
"id": "2",
"pid": "0",
"name": "服饰"
}, {
"id": "3",
"pid": "0",
"name": "化妆"
}, {
"id": "7",
"pid": "4",
"name": "空调"
}, {
"id": "8",
"pid": "4",
"name": "冰箱"
}, {
"id": "9",
"pid": "4",
"name": "洗衣机"
}, {
"id": "10",
"pid": "4",
"name": "热水器"
}, {
"id": "11",
"pid": "3",
"name": "面部护理"
}, {
"id": "12",
"pid": "3",
"name": "口腔护理"
}, {
"id": "13",
"pid": "2",
"name": "男装"
}, {
"id": "14",
"pid": "2",
"name": "女装"
}, {
"id": "15",
"pid": "7",
"name": "海尔空调"
}, {
"id": "16",
"pid": "7",
"name": "美的空调"
}, {
"id": "19",
"pid": "5",
"name": "加湿器"
}, {
"id": "20",
"pid": "5",
"name": "电熨斗"
}];
let attrdata = {
defaultdata: "0" //设置默认父id
}
function tree(data, attrdata) {
let result = [] //存储返回结果
if (data && data.length > 0) { //判断传入数组是否有值
for (let key of data) {//循环该数组
if (key.pid == attrdata.defaultdata) {//匹配一级元素
let obj={}//存储我想要得属性
//这里也可以增加自己想要属性
let child = getChild(key.id, data);//匹配children 需要自身ID 数组
if(child&&child.length>0){
obj.children=child
}
obj=Object.assign(key,obj)//合并数据
result.push(obj);
}
}
}
return result
}
//getChild 方法和上述一样
function getChild(pid,data){
let result = []
if (data && data.length > 0) {
for (let key of data) {
if (key.pid == pid) {
let obj={}//存储我想要得属性
//这里也可以增加自己想要属性
let child = getChild(key.id, data);//匹配children 需要自身ID 数组
if(child&&child.length>0){
obj.children=child
}
obj=Object.assign(key,obj)//合并数据
result.push(obj); //添加返回chidren数组
}
}
}
return result
}
const arr = [
{id: 'A', pId: null, name: 'A'},
{id: 'C', pId: 'A', name: 'C'},
{id: 'D', pId: null, name: 'D'},
{id: 'E', pId: 'C', name: 'E'},
{id: 'C', pId: null, name: 'D'},
{id: 'B', pId: 'A', name: 'B'},
]
function generateTree(nodeList) {
const nodeMap = nodeList.reduce((acc, cur) => {
acc[cur.id] = cur
return acc
}, {})
const res = []
nodeList.forEach(node => {
if (!node.pId) {
res.push(node)
return
}
const parentNode = nodeMap[node.pId]
parentNode.children= [...(parentNode.children || []), node]
console.log((parentNode.children || []))
console.log( node)
})
return res
}