const list = [
{ id: 1, pid: 0, name: '天津' },
{ id: 2, pid: 1, name: '河西区' },
{ id: 3, pid: 1, name: '滨海新区' },
{ id: 4, pid: 1, name: '津南' },
{ id: 5, pid: 1, name: '西青' },
{ id: 6, pid: 3, name: '胡家园' },
{ id: 7, pid: 3, name: '工人新村' },
{ id: 8, pid: 3, name: '人民广场' }
];
const arrayToTree = (arr, pid) => {
return arr.reduce((res, current) => {
if (current['pid'] === pid) {
current.children = arrayToTree(arr, current['id']);
return res.concat(current);
}
return res;
}, []);
};
console.log(arrayToTree(list, 0))