javascript - Nesting a parent child relationship in lodash, given the parent id and children -


how able nest json object if parent , children given property.

the data looks like:

   "1": {         "id": 1,         "name": "foo",         "parent": null,         "root": 1,         "children": [2, 4, 6],         "posts":[             { "id": "1", "name": "item1" },             { "id": "2", "name": "item2" },             { "id": "3", "name": "item3" }         ]     },     "2": {         "id": 2,         "name": "bar",         "parent": 1,         "root": 1,         "children": null,         "posts":[             { "id": "4", "name": "item4" }         ]     },     "3": {         "id": 3,         "name": "bazz",         "parent": null,         "root": 3,         "children": [5, 7],         "posts":[             { "id": "5", "name": "item5" },             { "id": "6", "name": "item6" }         ]     },    .... 

a simple groupby using lodash won't it.

var group = _.groupby(data, 'parent'); 

here fiddle:

http://jsfiddle.net/tzugzo8a/1/

the context of question nested categories subcategories, , categories can have categories , posts in them.

basically don't want have different property children , posts, since children of parent.

desired output

    "1": {         "id": 1,         "name": "foo",         "parent": null,         "root": 1,         "iscategory": true,         "children": [              {                  "id": 2,                  "name": "bar",                  "parent": 1,                  "root": 1,                  "iscategory": true,                  "children": null              },              { "id": "1", "name": "item1", iscategory: false },              { "id": "2", "name": "item2", iscategory: false },              { "id": "3", "name": "item3", iscategory: false }          ]         ...     } 

this take on question (fiddle):

var data = getdata();  var group = gettree(data);  console.log(group);  function gettree(flat) {     return _.reduce(flat, function (treeobj, item, prop, flattree) {         var children = _.map(item.children, function (childid) {             return _.set(flattree[childid], 'iscategory', true);         }).concat(_.map(item.items, function(item) {             return _.set(item, 'iscategory', false);         }));          item.children = !!children.length ? children : null;          delete item.items;          item.parent === null && (treeobj[prop] = item);          return treeobj;     }, {}); } 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -