前端转化树结构1
后端关系型数据库
var data = [{
"province": "浙江",
"city": "杭州",
"name": "西湖"
}, {
"province": "四川",
"city": "成都",
"name": "锦里"
}, {
"province": "四川",
"city": "成都",
"name": "方所"
}, {
"province": "四川",
"city": "阿坝",
"name": "九寨沟"
}]
转化为
var data = [{
"value": "浙江",
"children": [{
"value": "杭州",
"children": [{
"value": "西湖"
}]
}]
}, {
"value": "四川",
"children": [{
"value": "成都",
"children": [{
"value": "锦里"
}, {
"value": "方所"
}]
}, {
"value": "阿坝",
"children": [{
"value": "九寨沟"
}]
}]
}]
直接上转化函数:
transObject(tableData, keys) {
let hashTable = {},
res = [];
for (let i = 0; i < tableData.length; i++) {
let arr = res,
cur = hashTable;
for (let j = 0; j < keys.length; j++) {
let key = keys[j],
filed = tableData[i][key];
if (!cur[filed]) {
let pusher = {
value: filed,
},
tmp;
if (j !== keys.length - 1) {
tmp = [];
pusher.children = tmp;
}
cur[filed] = { $$pos: arr.push(pusher) - 1 };
cur = cur[filed];
arr = tmp;
} else {
cur = cur[filed];
arr = arr[cur.$$pos].children;
}
}
}
return res;
},
使用:
this.transObject(list, ["province", "city", "name", "title"])