javascript - Group by on JSON array using Underscore JS -
i have json array object follows:
var orders = [{ orderid: 1, firstname: 'john', lastname: 'smith', address: { street: '123 main street', city: 'new york', zip: 10001 } }, { orderid: 2, firstname: 'john', lastname: 'smith', address: { street: '456 main street', city: 'new york', zip: 10001 } }, { orderid: 3, firstname: 'john', lastname: 'smith', address: { street: '123 main street', city: 'new york', zip: 10001 } }, { orderid: 4, firstname: 'john', lastname: 'smith', address: { street: '123 main street', city: 'new york', zip: 10002 } }]; i trying use underscore.js create new array object, grouped address meet use case of displaying orders have been shipped 123 main street, new york, 1001.
is underscore.js right approach this? if so, how should so? hints helpful.
see _.groupby
console.log(_.groupby(orders, function(obj){ return obj.address.street + '|' + obj.address.city + '|' + obj.address.zip; })); see http://jsfiddle.net/mendesjuan/gc47ruyl/1/
this example assumes cannot have | in address, may need better separator, or use json.stringify:
console.log(_.groupby(orders, function(obj){ return json.stringify([obj.address.street, obj.address.city, obj.address.zip]); }));
Comments
Post a Comment