[英]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. 任何提示都会有所帮助。
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]);
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.