我有以下数组:
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 }
]
}
];
答案 0 :(得分:2)
你想要的群组重载如下:
// Overload:function(keySelector,elementSelector,resultSelector,compareSelector)
首先,您需要一个密钥,它是分销商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。
答案 1 :(得分:0)
这应该可以解决问题:
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 }
];
var dest = [];
source.map(function(current){
var id = current.DistributorId - 1;
dest[id] = dest[id] || {
"DistributorId": current.DistributorId,
"DistributorName": current.DistributorName,
"PriceLists": []
};
dest[id].PriceLists.push({ "Year": current.Year, "Month": current.Month });
})