underscore.js - Group objects by property in javascript -
how convert this:
[ {food: 'apple', type: 'fruit'}, {food: 'potato', type: 'vegetable'}, {food: 'banana', type: 'fruit'}, ]
into this:
[ {type: 'fruit', foods: ['apple', 'banana']}, {type: 'vegetable', foods: ['potato']} ]
using javascript or underscore
assuming original list contained in variable named list
:
_ .chain(list) .groupby('type') .map(function(value, key) { return { type: key, foods: _.pluck(value, 'food') } }) .value();
Comments
Post a Comment