我有以下数组:
var source = [
{ "DistributorId": 1, "DistributorName": "Distributor 01", "PriceListId": 1, "Year": 2014, "Month": 9 },
{ "DistributorId": 1, "DistributorName": "Distributor 01", "PriceListId": 2, "Year": 2014, "Month": 10 },
{ "DistributorId": 2, "DistributorName": "Distributor 02", "PriceListId": 3, "Year": 2014, "Month": 10 },
{ "DistributorId": 3, "DistributorName": "Distributor 03", "PriceListId": 4, "Year": 2014, "Month": 9 },
{ "DistributorId": 3, "DistributorName": "Distributor 03", "PriceListId": 5, "Year": 2014, "Month": 10 }
];
我想使用 linq.js 按两个字段“DistributorId”和“DistributorName”对这些数组进行分组 得到以下结果:
var des =
[
{
"DistributorId": 1,
"DistributorName": "Distributor 01",
"PriceLists":
[
{ "Year": 2014, "Month": 9 },
{ "Year": 2014, "Month": 10 }
]
},
{
"DistributorId": 2,
"DistributorName": "Distributor 02",
"PriceLists":
[
{ "Year": 2014, "Month": 10 }
]
},
{
"DistributorId": 3,
"DistributorName": "Distributor 03",
"PriceLists":
[
{ "Year": 2014, "Month": 9 },
{ "Year": 2014, "Month": 10 }
]
}
];
最佳答案
您想要的 group by 重载如下所示:
// Overload:function(keySelector,elementSelector,resultSelector,compareSelector)
首先,您需要 key ,它是分销商 ID 和名称的组合。 然后收集具有相同经销商 ID 和名称的所有年份和月份。 结果当然是比较关键对象的方法(将属性作为字符串是实现该目的的一种简单方法)。
var query = Enumerable.from(data)
.groupBy(
"{ Id: $.DistributorId, Name: $.DistributorName }",
"{ Year: $.Year, Month: $.Month }",
"{ DistributorId: $.Id, DistributorName: $.Name, PriceLists: $$.toArray() }",
"String($.Id) + $.Name"
)
.toArray();
请注意,我使用的是 linq.js 3.x 名称:使用 lowerCamelCase 的方法。旧版本更改为 UpperCamelCase。
关于javascript - Linq.js : Group By two properties (fields),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26095424/