Last active
April 4, 2020 04:26
-
-
Save deepakshrma/74abb6e844fca40616af5f391453cca1 to your computer and use it in GitHub Desktop.
Create tree out of sorted data.
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 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