Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. (Reproduced please indicate the source) https://blog.csdn.net/zhangjing0320/article/details/84104406
This method has its limitations, must know the root of the parent. I wrote it myself, have questions, please leave a message told grateful.
var data = [{
id: 6,
parent: 0,
name: '北京市'
}, {
id: 1,
parent: 0,
name: '河北省'
}, {
id: 4,
parent: 2,
name: '唐县'
}, {
id: 5,
parent: 2,
name: '顺平'
}, {
id: 7,
parent: 6,
name: '朝阳区'
}, {
id: 8,
parent: 6,
name: '东城区'
}, {
id: 2,
parent: 1,
name: '保定'
}, {
id: 3,
parent: 1,
name: '沧州'
}];
function changeToTree(data) {
var arr = [];
var obj = {};
for (var i = 0; i < data.length; i++) {
if (data[i].parent === 0) {
arr.push(
Object.assign({}, data[i], {
children: []
})
);
} else {
if (!obj[data[i].parent]) {
obj[data[i].parent] = [];
}
obj[data[i].parent].push(
Object.assign({}, data[i], {
children: []
})
);
}
}
callback(arr, obj);
return arr;
}
function callback(arr, obj) {
for (var j = 0;j < arr.length; j++) {
for (var i = 0;i < Object.keys(obj).length; i++) {
var id = arr[j].id;
if (obj[id]) {
arr[j].children = [].concat(obj[id]);
delete obj[id];
} else {
callback(arr[j].children, obj);
}
}
}
if (Object.keys(obj).length > 0) {
for (var j = 0;j < arr.length; j++) {
for (var i = 0;i < Object.keys(obj).length; i++) {
callback(arr[j].children, obj);
}
}
}
}
console.log(changeToTree(data));
result:
I think a good follow-up and other methods, or see a good way to write again.