Created
November 4, 2023 05:08
-
-
Save ZacharyBear/5fafa7c12099d4f121db5edea38b3e48 to your computer and use it in GitHub Desktop.
Print tree node list, generate structure string and find childrens
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const nodes = [ | |
{ id: 1 }, | |
{ id: 2, pid: 1 }, | |
{ id: 3, pid: 1 }, | |
{ id: 4, pid: 2 }, | |
{ id: 5, pid: 2 }, | |
{ id: 6, pid: 3 }, | |
{ id: 7, pid: 3 }, | |
{ id: 8, pid: 3 }, | |
] | |
const getChildrenIds = (parentId, all) => { | |
let result = [] | |
for (key in all) { | |
let node = all[key]; | |
if (node.pid === parentId) { | |
result.push(node.id) | |
const childrenIds = getChildrenIds(node.id, all) | |
if (childrenIds.length !== 0) { | |
result.push(...childrenIds) | |
} | |
} | |
} | |
return result // children id | |
} | |
const getStruct = (id, all) => { | |
const target = all.filter(node => node.id === id)[0] | |
if (target.pid) { | |
return getStruct(target.pid, all) + '/' + id | |
} | |
return target.id | |
} | |
const printNode = (id, all) => { | |
const childrenIds = getChildrenIds(id, all); | |
for (const key in childrenIds) { | |
const node = all[key] | |
const struct = getStruct(node.id, all) | |
console.log(`id: ${node.id}\t struct:${struct}`); | |
} | |
} | |
console.log("Children:", getChildrenIds(1, nodes)) | |
console.log("Structure:", getStruct(5, nodes)) | |
printNode(1, nodes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment