Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function buildTree(nodes) {
- var lookup = {};
- var tree = [];
- nodes.forEach(function (node) {
- node.children = [];
- lookup[node.id] = node;
- });
- nodes.forEach(function (node) {
- if (node.parentid != null) {
- var parent = lookup[node.parentid];
- parent.children.push(node);
- } else {
- tree.push(node);
- }
- });
- console.log(tree);
- return tree;
- }
- var test = [{
- 'id': 1,
- 'parentid': null
- }, {
- 'id': 2,
- 'parentid': 1
- }, {
- 'id': 3,
- 'parentid': 1
- }, {
- 'id': 4,
- 'parentid': 3
- }, {
- 'id': 5,
- 'parentid': null
- }, {
- 'id': 6,
- 'parentid': 5
- }];
- buildTree(test);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement