1 回答

TA貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個贊
大概寫了一下,應(yīng)該可以改改,有些特殊情況沒考慮吧
var value = [{
"parentId": 0,
"nodeId": 20,
"nodeLevel": 1,
"nodeName": "老板"
}, {
"parentId": 20,
"nodeId": 30,
"nodeLevel": 2,
"nodeName": "黃經(jīng)理"
}, {
"parentId": 20,
"nodeId": 32,
"nodeLevel": 2,
"nodeName": "張經(jīng)理"
}, {
"parentId": 30,
"nodeId": 37,
"nodeLevel": 3,
"nodeName": "黃經(jīng)理下屬主管"
}, {
"parentId": 32,
"nodeId": 56,
"nodeLevel": 3,
"nodeName": "張經(jīng)理下屬主管"
}];
var data = value.reduce(function(pre, cur) {
pre = new Object(pre);
cur = new Object(cur);
return parse(pre, cur);
});
function parse(a, b) {
if (a.parentId === b.nodeId) {
if (b.children) {
b.children.push(a);
} else {
b.children = [a];
}
return b;
} else if (b.parentId === a.nodeId) {
if (a.children) {
a.children.push(b);
} else {
a.children = [b];
}
return a;
} else {
if (a.nodeLevel < b.nodeLevel && a.children) {
for (let node of a.children) {
let r = parse(node, b);
if (r) {
a.children.map(v=>{
if (v.nodeId === r.nodeId) {
return r;
}
return v;
}
);
}
}
return a;
} else if (a.nodeLevel > b.nodeLevel && b.children) {
for (let node of b.children) {
let r = parse(node, a);
if (r) {
b.children.map(v=>{
if (v.nodeId === r.nodeId) {
return r;
}
return v;
}
);
}
}
return b;
}
}
}
function format(data) {
if (!data) {
return;
}
var r = {
"value": data.nodeName
};
if (data.children) {
r.children = [];
for (let child of data.children) {
r.children.push(format(child));
}
}
return r;
}
data = format(data);
console.log(JSON.stringify(data));
添加回答
舉報(bào)