方案1:
fn() {
var setting={idKey:'id',parentKey:'pId',childKey:'children'};
let data = this.transformTozTreeFormat(setting,divisionAll); //divisionAll json数据
this.options = data;
},
transformTozTreeFormat(setting, sNodes) {
var i,l,
key = setting.idKey,
parentKey = setting.parentKey,
childKey = setting.childKey;
if (!key || key=="" || !sNodes) return [];
var r = [];
var tmpMap = {};
for (i=0, l=sNodes.length; i<l; i++) {
tmpMap[sNodes[i][key]] = sNodes[i];
}
for (i=0, l=sNodes.length; i<l; i++) {
if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
if (!tmpMap[sNodes[i][parentKey]][childKey])
tmpMap[sNodes[i][parentKey]][childKey] = [];
tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
} else {
r.push(sNodes[i]);
}
}
return r;
},
方案2:
generateDivision() {
// 暂时使用纯json数据,考虑采用数据库结构
const list = divisionAll //divisionAll json数据
const result = []
if (!Array.isArray(list)) {
return result
}
list.forEach(item => {
delete item.children
})
console.log(list)
const map = {}
list.forEach(item => {
map[item.id] = item
})
console.log(list)
list.forEach(item => {
const parent = map[item.pId]
if (parent.id !== item.id) {
(parent.children || (parent.children = [])).push(item)
} else {
result.push(item)
}
})
this.options = result
console.log(this.options)
},