Skip to content

Instantly share code, notes, and snippets.

@zzjin23
Last active June 8, 2020 06:04
Show Gist options
  • Save zzjin23/7cc834616bbc9be5d5c8300ff540c4eb to your computer and use it in GitHub Desktop.
Save zzjin23/7cc834616bbc9be5d5c8300ff540c4eb to your computer and use it in GitHub Desktop.
array object to tree
const nodeList = [
{"id":1,"parentId":0,"name":"AA"},
{"id":2,"parentId":1,"name":"BB"},
{"id":3,"parentId":1,"name":"CC"},
{"id":4,"parentId":3,"name":"DD"},
{"id":5,"parentId":3,"name":"EE"},
{"id":6,"parentId":2,"name":"FF"},
{"id":7,"parentId":2,"name":"GG"},
{"id":8,"parentId":4,"name":"HH"},
{"id":9,"parentId":5,"name":"II"}
];
nodeList.forEach(n1 => {
nodeList.forEach(n2 => {
if (n2.id == n1.parentId) {
if (!n2.childNodes) n2.childNodes = [];
n2.childNodes.push(n1);
}
});
});
nodeList.sort((f,s) => f.parentId - s.parentId);
const tabStr = ' ';
console.log(nodeList[0].name);
const printNode = function(n, index) {
if (n.childNodes) {
n.childNodes.forEach((nn, i) => {
console.log(tabStr.repeat(index) + nn.name);
if (nn.childNodes && nn.childNodes.length > 0) {
printNode(nn, index+1);
}
});
}
}
printNode(nodeList[0], 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment