Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create recursive tree from json using lodash transform without recursion. Can have unlimited nesting.
var _ = require('lodash');
var arr = [
{"name":"my2child1","title":"My 2 Child 1","parent":"my2"},
{"name":"my2child2","title":"My 2 Child 2","parent":"my2"},
{"name":"parent","title":"A single parent"},
{"name":"child-parent","title":"A child parent","parent":"child1"},
{"name":"my","title":"My"},
{"name":"my2","title":"My2"},
{"name":"child1","title":"Child 1","parent":"my"},
{"name":"child2","title":"Child 2","parent":"my"}
];
var result = _.filter(arr, function(item){
var parentName = item.parent;
item.children = this(item.name);
return !(parentName && this(parentName).push(item));
}, _.memoize(function(){ return []; }));
console.log(JSON.stringify(result, null, 2));
// ==> output
//[
// {
// "name": "parent",
// "title": "A single parent",
// "children": []
// },
// {
// "name": "my",
// "title": "My",
// "children": [
// {
// "name": "child1",
// "title": "Child 1",
// "parent": "my",
// "children": [
// {
// "name": "child-parent",
// "title": "A child parent",
// "parent": "child1",
// "children": []
// }
// ]
// },
// {
// "name": "child2",
// "title": "Child 2",
// "parent": "my",
// "children": []
// }
// ]
// },
// {
// "name": "my2",
// "title": "My2",
// "children": [
// {
// "name": "my2child1",
// "title": "My 2 Child 1",
// "parent": "my2",
// "children": []
// },
// {
// "name": "my2child2",
// "title": "My 2 Child 2",
// "parent": "my2",
// "children": []
// }
// ]
// }
//]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment