Created
March 25, 2015 21:04
-
-
Save cef62/9cfe06915e9a9ce9e374 to your computer and use it in GitHub Desktop.
Create a hierarchical structure starting from a flatten array of nodes
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
(function() { | |
'use strict'; | |
// original data source | |
var source = [{ | |
"id": 105142, | |
"text": "root level", | |
"parent": null | |
}, { | |
"id": 105150, | |
"text": "root level", | |
"parent": null | |
}, { | |
"id": 105195, | |
"text": "root level", | |
"parent": null | |
}, { | |
"id": 105190, | |
"text": "first level", | |
"parent": 105195, | |
}, { | |
"id": 105193, | |
"text": "root level", | |
"parent": null | |
}, { | |
"id": 105795, | |
"text": "first level", | |
"parent": 105193 | |
}, { | |
"id": 105197, | |
"text": "second level", | |
"parent": 105203 | |
}, { | |
"id": 105203, | |
"text": "first level", | |
"parent": 105193 | |
}]; | |
_.remove(source, | |
function lookForChildren(node, index, collection) { | |
if (node.parent) { | |
// look for parent | |
var parent = _.find(collection, {id: node.parent}); | |
if (parent) { | |
// init parent children field | |
parent.children = parent.children || []; | |
// add to parent | |
parent.children.push(node); | |
} | |
// remove it | |
return true; | |
} | |
} | |
); | |
// print hierarchical collection | |
console.log(source); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment