Skip to content

Instantly share code, notes, and snippets.

@deepakshrma
Last active April 4, 2020 04:26
Show Gist options
  • Save deepakshrma/74abb6e844fca40616af5f391453cca1 to your computer and use it in GitHub Desktop.
Save deepakshrma/74abb6e844fca40616af5f391453cca1 to your computer and use it in GitHub Desktop.
Create tree out of sorted data.
const source = [
{ 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" },
];
function tree(data, id, pId) {
const [result] = data.reduce(
([r, map], item) => {
const d = { ...item, children: [] };
const loc = map[item[pId]];
if (loc) {
loc.children.push(d);
} else {
r.push(d);
}
map[item[id]] = d;
return [r, map];
},
[[], {}]
);
return result;
}
console.log(JSON.stringify(tree(source, "Id", "Parent"), null, 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment