Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const arr = [
- { id: 1, parentid: 0 },
- { id: 4, parentid: 2 },
- { id: 3, parentid: 1 },
- { id: 5, parentid: 0 },
- { id: 6, parentid: 0 },
- { id: 2, parentid: 1 },
- { id: 7, parentid: 4 },
- { id: 8, parentid: 1 },
- { id: 9, parentid: 7 },
- { id: 10, parentid: 9 },
- { id: 11, parentid: 3 }
- ];
- function unflatten(arr) {
- const map = arr.reduce((pre, item) => {
- pre[item.id] = item;
- pre[item.id].children = [];
- return pre;
- }, {});
- const tree = [];
- Object.keys(map).forEach(id => {
- const value = map[id];
- if (value.parentid) {
- map[value.parentid].children.push(value);
- } else {
- tree.push(value);
- }
- });
- return tree;
- }
- const tree = unflatten(arr);
Add Comment
Please, Sign In to add comment