简体   繁体   中英

Group by on JSON array using Underscore JS

I have a JSON array object as 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 am trying to use underscore.js to create a new array object, grouped by the address to meet the use case of displaying all orders that have been shipped to 123 Main Street, New York, 1001 .

Is underscore.js the right approach to do this? If so, how should I do so? Any hints will be 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 you cannot have a | in an address, you may need a better separator, or use JSON.stringify :

console.log(_.groupBy(orders, function(obj){
    return JSON.stringify([obj.address.street, obj.address.city, obj.address.zip]);
}));

If you already have underscore in your page, you could use

var filteredOrders = _.filter(orders, function(order){
  return (order.address.street === '123 Main Street') &&
          (order.address.city === 'New York') &&
          (order.address.zip === 10001);
});

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM