简体   繁体   English

使用Underscore JS在JSON数组上分组

[英]Group by on JSON array using Underscore JS

I have a JSON array object as follows: 我有一个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
    }
}];

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

Is underscore.js the right approach to do this? underscore.js是正确的做法吗? If so, how should I do so? 如果是这样,我该怎么办? Any hints will be helpful. 任何提示都会有所帮助。

See _.groupBy _.groupBy

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

See http://jsfiddle.net/mendesjuan/gc47ruyL/1/ 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 : 在地址中,您可能需要更好的分隔符,或使用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 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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