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')         })     }); }); 

http://jsfiddle.net/bgazh/1/


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -