function array2tree(data, FieldName = "SCHEMENAME") {
const result = []
const map = data.reduce((pre, cur) => {
pre[cur.ID] = cur
return pre
}, {})
for (let item of data) {
if (item.PID == 0) {
item.id = item.ID
item.label = item[FieldName]
result.push(item)
continue
}
if (item.PID in map) {
const parent = map[item.PID]
parent.id = parent.ID
parent.label = parent[FieldName]
parent.children = parent.children || []
item.id = item.ID
item.label = item[FieldName]
parent.children.push(item)
}
}
return result
}
function convert(list) {
let result = [];
const map = list.reduce((pre, cur) => {
pre[cur.ID] = cur;
return pre;
}, {});
for (const item of list) {
if (item.PID === 0) {
result.push(item);
continue;
}
if (item.PID in map) {
let parent = map[item.PID];
parent.children = parent.children || [];
parent.children.push(item);
}
}
return result;
}
let list = [
{
"ID": 1,
"PID": 0,
"SCHEMENAME": "局内用户方案分组",
"REMARK": "",
"ADDTIME": "2022-09-14 15:51:27"
},
{
"ID": 2,
"PID": 1,
"SCHEMENAME": "气象台方案",
"REMARK": "",
"ADDTIME": "2022-09-14 15:51:59"
},
{
"ID": 3,
"PID": 2,
"SCHEMENAME": "haha案",
"REMARK": "",
"ADDTIME": "2022-09-14 15:51:59"
}
]
console.log(array2tree(list))
// console.log(convert(list))
console