-
-
Save danbete/e5790c053e235c4b8c4b5e5ca26b6ff3 to your computer and use it in GitHub Desktop.
Create recursive tree from json using lodash transform without recursion. Can have unlimited nesting.
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
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