我从另一个帖子中偷了这个脚本:
function convertToHierarchy() {
var arry = [
{ "Id": "1", "Name": "abc", "Parent": "", "attr": "abc" },
{ "Id": "2", "Name": "abc", "Parent": "1", "attr": "abc" },
{ "Id": "3", "Name": "abc", "Parent": "2", "attr": "abc" },
{ "Id": "4", "Name": "abc", "Parent": "2", "attr": "abc" }
];
var nodeObjects = createStructure(arry);
for (var i = nodeObjects.length - 1; i >= 0; i--) {
var currentNode = nodeObjects[i];
if (currentNode.value.Parent === "") {
continue;
}
var parent = getParent(currentNode, nodeObjects);
if (parent === null) {
continue;
}
parent.children.push(currentNode);
nodeObjects.splice(i, 1);
}
console.dir(nodeObjects);
return nodeObjects;
}
function createStructure(nodes) {
var objects = [];
for (var i = 0; i < nodes.length; i++) {
objects.push({
value: nodes[i],
children: []
});
}
return objects;
}
function getParent(child, nodes) {
var parent = null;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].value.Id === child.value.Parent) {
return nodes[i];
}
}
return parent;
}
该脚本产生:
[{
"value": {
"Id": "1",
"Name": "abc",
"Parent": "",
"attr": "abc"
},
"children": [{
"value": {
"Id": "2",
"Name": "abc",
"Parent": "1",
"attr": "abc"
},
"children": [{
"value": {
"Id": "4",
"Name": "abc",
"Parent": "2",
"attr": "abc"
},
"children": []
}, {
"value": {
"Id": "3",
"Name": "abc",
"Parent": "2",
"attr": "abc"
},
"children": []
}]
}]
}]
我正在寻找的是:
[{
"Id": "1",
"Name": "abc",
"Parent": "",
"attr": "abc",
"children": [{
"Id": "2",
"Name": "abc",
"Parent": "1",
"attr": "abc",
"children": [{
"Id": "4",
"Name": "abc",
"Parent": "2",
"attr": "abc"
}, {
"Id": "3",
"Name": "abc",
"Parent": "2",
"attr": "abc"
}]
}]
}]
我需要首先摆脱“价值”包装,其次是空子节点。我知道我可以编写一个清理脚本,但这不是最佳实践。如果有人知道如何修复或建议不同的脚本,那就太好了!
谢谢