Linq.js:按两个属性(字段)分组
Linq.js : Group By two properties (fields)
我有以下数组:
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"answers"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)
首先,您需要一个密钥,它是分发服务器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.js3.x名称:使用lowerCamelCase的方法。旧版本更改为UpperCamelCase。
这应该可以做到:
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 });
})
相关文章:
- 如何使用jquery将两个字段组合为下拉菜单中的选项
- Angularjs 通过选择不同选择框中的两个字段来填充选择框
- 使用Join,要求两个字段中的一个字段为非空
- 使用一个提交按钮验证两个字段
- 如何使用angular ui select过滤两个字段中的数据
- jQuery ui自动完成下拉列表中的两个字段
- Jquery使用PHP和MySQL基于一个字段自动完成两个字段
- 比较 angularjs 指令中的两个字段
- 如何根据返回的 Json 更新两个字段
- 当两个字段为空时如何显示错误消息 javascript/jquery.
- 比较两个字段的验证
- 如何对具有两个字段的对象进行排序
- 对对象的两个字段进行角度ng重复搜索
- 使用 Javascript 的 HTML 中两个字段之间的区别
- 懒惰.js如何选择两个字段的不同(uniq)
- jQuery 验证:验证一个字段或一对的两个字段是否为必填字段
- 如何对此 javascript 函数进行编码以在选择特定类型时显示两个 + 字段集
- 记住密码基于两个字段
- 匹配 JavaScript 中两个函数中表单中的两个字段
- 使两个字段的组合在我的收藏中独一无二