javascript - Linq.js : Group By two properties (fields)

标签 javascript group-by linq.js

我有以下数组:

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/

相关文章:

c# - LINQ GroupBy混淆

r - ggplot2:为每组平均值添加线(错误:没有名为 StatHline 的统计数据。)

javascript - Typescript 检查 "any n consecutive elements are same"是否在 M 大小的数组中

javascript - 如何使用 linqjs 对 json 结果进行分组和计数

javascript - contenteditable div 中突出显示的文本 : Get the start and the end of the highlighted text

MySQL-如何按组求和计数

javascript - 将 bootstrap-slider 与 jQuery UI 结合使用

javascript - 具有空值的 Linq.JS OrderBy

javascript - 从事件监听器返回一个变量

javascript - 在 asp.net mvc 4 中组织自定义 javascript