Skip to content

Instantly share code, notes, and snippets.

@ozluy
Created March 25, 2023 21:19
Show Gist options
  • Save ozluy/f4c1f7995d4b727656b7421960a2e5f8 to your computer and use it in GitHub Desktop.
Save ozluy/f4c1f7995d4b727656b7421960a2e5f8 to your computer and use it in GitHub Desktop.
People.ai
const data = [
{ id: 1, name: "San Francisco", parent: 5 },
{ id: 2, name: "Los Angeles", parent: 5 },
{ id: 3, name: "San Diego", parent: 5 },
{ id: 4, name: "Tucson", parent: 7 },
{ id: 5, name: "California", parent: 6 },
{ id: 6, name: "USA", parent: null },
{ id: 7, name: "Arizona", parent: 6 },
{ id: 8, name: "Tukey", parent: null },
{ id: 9, name: "Istanbul", parent: 8 },
{ id: 10, name: "Besiktas", parent: 9 },
{ id: 11, name: "Kadikoy", parent: 9 },
{ id: 12, name: "Czechia", parent: null },
{ id: 13, name: "Prague", parent: 12 },
{ id: 14, name: "Karlin", parent: 13 },
{ id: 15, name: "Brno", parent: 12 }
];
const convertToTree = (data) => {
let tree = { children: [] };
while (data.length > 0) {
data.map((item, index) => {
if (item.parent === null) {
tree = { ...tree, children: [...tree.children, ...[item]] };
data.splice(index, 1);
} else {
const handleChildren = (tree) =>
(tree.children || []).map((child) => {
if (child.id === item.parent) {
child.children = [...(child.children || []), ...[item]];
data.splice(index, 1);
} else {
handleChildren(child);
}
return child;
});
tree.children = handleChildren(tree);
}
return item;
});
console.log(data.length);
}
return tree;
};
console.log(JSON.stringify(convertToTree(data), {}, Infinity));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment