在平时项目中通常会遇到树形图,但是后端又没有给你返回这种类型的数据,那就需要自己转换数据结构。
将下列格式转为tree树形结构
let data =[
{
code: "1",
name: "空调机组3号",
longitude: "120.1054122",
latitude: "30.3078394",
first: "杭州市",
second: "西湖区"
},
{
code: "2",
name: "空调机组1号",
longitude: "121.3682650",
latitude: "31.1419520",
first: "上海市",
second: "闵行区"
},
{
code: "3",
name: "测试1号",
longitude: "121.3682650",
latitude: "31.1419520",
first: "上海市",
second: "闵行区"
},
{
code: "4",
name: "测试2号",
longitude: "121.3682650",
latitude: "31.1419520",
first: "上海市",
second: "静安区"
},
{
code: "C7DB5C30",
name: "空调机组2号",
longitude: "121.3682650",
latitude: "118.915388",
first: "南京市",
second: "江宁区"
}]
function treeData (data) {
var newData = [], hash = {};
for (let i = 0; i < data.length; i++) {
if (!hash[data[i].first]) {
hash[data[i].first] = {
'label': data[i].first
};
hash[data[i].first]['children'] = [{
'label': data[i].second
}];
for (let j = 0; j < hash[data[i].first].children.length; j++) {
hash[data[i].first].children[j]['children'] = [{
'label': data[i].name,
'code': data[i].code,
'long': data[i].longitude,
'lat': data[i].latitude,
}];
}
newData.push(hash[data[i].first]);
} else {
try {
for (let k = 0; k < hash[data[i].first].children.length; k++) {
if (hash[data[i].first].label == data[i].first &&
hash[data[i].first].children[k].label == data[i].second) { // 判断一级目录、二级目录都相同
hash[data[i].first].children[k]['children'].push({
'label': data[i].name,
'code': data[i].code,
'long': data[i].longitude,
'lat': data[i].latitude,
})
throw new Error()
}
}
if (hash[data[i].first].label == data[i].first) { // 判断一级目录相同
hash[data[i].first]['children'].push({
'label': data[i].second,
'children': [{
'label': data[i].name,
'code': data[i].code,
'long': data[i].longitude,
'lat': data[i].latitude,
}]
})
}
} catch (error) {
console.log(error)
}
}
}
return newData;
}