使用Underscore JS在JSON数组上分组

时间:2014-12-01 22:39:27

标签: javascript underscore.js

我有一个JSON数组对象如下:

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
    }
}];

我正在尝试使用underscore.js创建一个新的数组对象,按地址分组,以满足显示已发送到123 Main Street, New York, 1001的所有订单的用例。

underscore.js是否有正确的方法来做到这一点?如果是这样,我该怎么办?任何提示都会有所帮助。

2 个答案:

答案 0 :(得分:3)

请参阅_.groupBy

console.log(_.groupBy(orders, function(obj){
    return obj.address.street + '|' + obj.address.city + '|' + obj.address.zip;
}));

请参阅http://jsfiddle.net/mendesjuan/gc47ruyL/1/

此示例假设您在地址中没有|,您可能需要更好的分隔符,或使用JSON.stringify

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

答案 1 :(得分:2)

如果您的网页中已经有下划线,则可以使用

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

Fiddle