javascript - groupBy array of objects with underscore.js -


i have array (order) of objects (products): , want group , count these products id:

var order = [ { product_id: 70, product_price: 9, product_color: "ccc"}, { product_id: 70, product_price: 9, product_color: "ccc"}, { product_id: 71, product_price: 10, product_color: "fff" } ]; 

with underscore.js:

var groups = _.countby(order, function(value){     return value.product_id + "#" + value.product_price + "#" + value.product_color; }) //--> object {70#ccc#9: 2, 71#fff#10: 1} 

so works… now, how can return theses values array this, can work new array of objects?

 [     { product_id: 70, product_price: 9, product_color: "ccc", count: 2},     { product_id: 70, product_price: 9, product_color: "fff", count: 1}  ]; 

instead of countby use groupby , map across groups add count:

var groups = _.groupby(order, function(value){     return value.product_id + "#" + value.product_price + "#" + value.product_color; })  groups = _.map(groups, function(group){     return _.extend(group[0], {count: group.length}); }); 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -