数据:
date :[
{ id: 1, pid: 0, name: '中国' },
{ id: 2, pid: 0, name: '巴铁' },
{ id: 3, pid: 1, name: '小日本儿' },
{ id: 4, pid: 2, name: '杂种美国' },
{ id: 5, pid: 2, name: '俄罗斯' },
{ id: 6, pid: 13, name: '乌克兰' },
{ id: 7, pid: 3, name: '英国' },
{ id: 8, pid: 7, name: '意大利' },
{ id: 9, pid: 7, name: '西班牙' }
]
方法:
created() {
console.log(this.convertToTree(this.date),123);
},
methods: {
convertToTree(flatData) {
let treeData = [];
let map = new Map();
let outputObj, pid;
for (let i = 0; i < flatData.length; i++) {
pid = flatData[i].pid;
if (map.has(pid)) {
if (!map.get(pid).childrens)
map.get(pid).childrens = [];
let obj = new Object(flatData[i]);
map.get(pid).childrens.push(obj);
map.set(flatData[i].id, obj);
} else if (!map.has(pid) && pid === 0) {
// '&& pid === 0' 判断条件是为了只将 pid 为 0 作为根节点,其它值不作为根节点。
// 如需将其它值也作为根节点,可将 'else if (!map.has(pid) && pid === 0)' 改为 'else'
outputObj = new Object(flatData[i]);
treeData.push(outputObj);
map.set(flatData[i].id, outputObj);
}
}
return treeData;
},