计算数据组的平均值

时间:2015-05-26 10:13:18

标签: javascript linq.js

我正在尝试为资源规划配置报告工具。我有一个JSON对象,其中包含有关我的句点(周)的信息以及该时段中某人的角色/体验(数字)。

我有两个人,戴夫和吉姆。在第1阶段(第1周),他们都在同一个团队(Tango)和第2阶段(第2周),只有Dave在一个团队中。

如何使用LINQ计算(并返回)每个时期每个团队的平均经验值?所以返回的值是:

Week 1: 2.5
Week 2: 3

我的JSON对象如下所示:

"persons": [
        {
            "id": "974d5090-5cf0-4742-a773-cbc17eaa3362",
            "periods": [
                {
                    "periodName": "Week1",
                    "teamName": "Tango",
                    "roleName": "SoftwareEngineerII",
                    "roleExperience": "2",
                    "id": "cc1f6e14-40f6-4a79-8c66-5f3e773e0929"
                },
                {
                    "periodName": "Week2",
                    "teamName": "Tango",
                    "roleName": "SoftwareEngineerIII",
                    "roleExperience": "3",
                    "id": "bc121b26-b020-4029-8a95-b92cb333bc90"
                }
            ],
            "personName": "Dave"
        },
        {
            "id": "341aeea2-4bf1-4e81-a03e-9bff7babad79",
            "periods": [
                {
                    "periodName": "Week1",
                    "teamName": "Tango",
                    "roleName": "SoftwareEngineerIII",
                    "roleExperience": "3",
                    "id": "db7b642c-4502-4a59-8a32-b5bae5ed5195"
                },
                {
                    "periodName": "Week2",
                    "teamName": "-",
                    "roleName": "-",
                    "roleExperience": "-",
                    "id": "6d9a083b-8762-4a37-a659-e9c8bf5baeb5"
                },

            ],
            "personName": "Jim"
        },
        ...
    ]

1 个答案:

答案 0 :(得分:0)

您需要将数据投影到不同的时期和年份。过滤掉没有有效时间的时段并将它们分组,以便取得平均值。

var query = Enumerable.From(data.persons)
    .SelectMany(
        "$.periods",
        "{ periodName: $$.periodName, roleExperience: Number($$.roleExperience) }")
    .Where("!isNaN($.roleExperience)")
    .GroupBy(
        "$.periodName",
        "$.roleExperience",
        "{ Period: $, Average: $$.Average() }")
    .ToArray();