javascript - Nest or unflatten array -
i have array of objects looks this.
var arr = [{'id':21 ,'name' : 'name 1' ,'vehiclename' : 'vehicle 1' ,'parentid' : 21}, {'id':21 ,'name' : 'name 1' ,'vehiclename' : 'vehicle 2' ,'parentid' : 21}, {'id':22 ,'name' : 'name 2' ,'vehiclename' : 'vehicle 1' ,'parentid' : 22}, {'id':22 ,'name' : 'name 2' ,'vehiclename' : 'vehicle 2' ,'parentid' : 22}]
i unflatten or group array this.
var arr = [{'id':21, name: 'name 1' vehicles : [{'vehiclename':'vehicle 1','parentid':21}, {'vehiclename':'vehicle 2','parentid':21}] }, {'id':22, name: 'name 2' vehicles : [{'vehiclename':'vehicle 1','parentid':22}, {'vehiclename':'vehicle 2','parentid':22}] } }]
any appreciated.
for curious, here's underscore solution:
grouped = _.map(_.groupby(arr, 'id'), function(b) { return _.extend(_.pick(b[0], 'id', 'name'), { vehicles: _.map(b, function(elem) { return _.pick(elem, 'vehiclename', 'parentid') }) }); });
Comments
Post a Comment