How to split javascript array of object with specific condition using lodash/underscorejs -


i have array of objects this:

var data = [  {     type : "parent",     name : "a"  },  {     type : "child",     name : "1"  },  {     type : "child",     name : "2"  },  {     type : "parent",     name : "b"  },  {     type : "child",     name : "3"  } ] 

and want move child objects parent objects, splitted parrent object (there no given key child object belonged parrent). it's separate parent object. simple want change array :

[   {     type : "parent",     name : "a",     child: [         {             type : "child",             name : "1"         },         {             type : "child",             name : "2"         }     ]   },   {     type : "parent",     name : "b",     child: [         {             type : "child",             name : "3"         }       ]   } ] 

i have read lodash chunk it's no use.

you can use either native array.prototype.reduce function or lodash's reduce:

var data = [  {     type : "parent",     name : "a"  },  {     type : "child",     name : "1"  },  {     type : "child",     name : "2"  },  {     type : "parent",     name : "b"  },  {     type : "child",     name : "3"  } ];  // if using _.reduce use: // var newdata = _.reduce(data, function(arr, el) {...}, []); var newdata = data.reduce(function(arr, el) {   if (el.type === 'parent') {     // if el pushed directly reference     // original data object     arr.push({type: el.type, name: el.name, child: []});   }   else {     arr[arr.length - 1].child.push({type: el.type, name: el.name});   }    return arr; }, []); 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -