我在网上找了一段代码来转换,结果是符合要求的,但是代码一直看不懂,望社区朋友帮忙解释 原始数据 也就是data[0]
{
"data": [
{
"id": 1,
"pid": 0,
"name": "1",
"level": "1"
},
{
"id": 2,
"pid": 1,
"name": "1-1",
"level": "2"
},
{
"id": 3,
"pid": 2,
"name": "1-1-1",
"level": "3"
},
{
"id": 4,
"pid": 0,
"name": "2",
"level": "1"
},
{
"id": 5,
"pid": 4,
"name": "2-1",
"level": "2"
},
{
"id": 6,
"pid": 7,
"name": "3-1",
"level": "2"
},
{
"id": 7,
"pid": 0,
"name": "3",
"level": "1"
}
]
}
代码
// data[0]为原始数据
var hash = {};
var dataArr = [];
for (let i = 0; i < data[0].length; i++) {
hash[data[0][i].id] = data[0][i];
}
for (let i = 0; i < data[0].length; i++) {
var aVal = data[0][i];
var aValPar = hash[aVal['pid']];
if (aValPar) {
if (!aValPar.hasOwnProperty('children')) {
aValPar['children'] = [];
aValPar['children'].push(aVal);
} else {
aValPar['children'].push(aVal);
}
} else {
dataArr.push(aVal);
}
}
照我的理解 这段代码第二个for循环 每次aValPar都会被重新赋值,那么它的children不就没有了么,而且我推入dataArr的数据都是aVal,在第二个循环中没有对于aVal变量进行children 赋值,为什么结果中就会有chilren字段呢