Skip to content

Instantly share code, notes, and snippets.

@cef62
Created March 25, 2015 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cef62/9cfe06915e9a9ce9e374 to your computer and use it in GitHub Desktop.
Save cef62/9cfe06915e9a9ce9e374 to your computer and use it in GitHub Desktop.
Create a hierarchical structure starting from a flatten array of nodes
(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