在JavaScript

时间:2016-06-13 19:05:55

标签: javascript arrays json grouping

正如标题所说,我需要在分组对象中推送对象数组。我在这里找到了例子,它就是:

function groupBy(array, col, value) {
    var r = [], o = {};
    array.forEach(function (a) {
        if (!o[a[col]]) {
            o[a[col]] = {};
            o[a[col]][col] = a[col];
            o[a[col]][value] = 0;
            r.push(o[a[col]]);

        }
        o[a[col]][value] += +a[value];
    });
    return r;
};

var data = [{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }];

document.write('<pre>' + JSON.stringify(groupBy(data, 'Phase', 'Value'), 0, 4) + '</pre>');

我的结果是:

[
    {
        "Phase": "Phase 1",
        "Value": 50
    },
    {
        "Phase": "Phase 2",
        "Value": 130
    }
]

我想得到的是,我的分组对象内部是具有属性的对象数组:任务和值(对于我想要的每个任务的值)。

我试过了:

function groupBy(array, col, col2, value) {
    var r = [], o = {};
    array.forEach(function (a) {
        if (!o[a[col]]) {
            o[a[col]] = {};
            o[a[col]][col] = a[col];
            o[a[col]][col2] = a[col2];
            o[a[col]][value] = 0;
            r.push(o[a[col]]);

        }
        o[a[col]][value] += +a[value];
    });
    return r;
};

并添加&#34;任务&#34;参数,但只有我得到:

[
    {
        "Phase": "Phase 1",
        "Task" : "Task 1",
        "Value": 50
    },
    {
        "Phase": "Phase 2",
        "Task" : "Task 1",
        "Value": 130
    }
]

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您正在使用PhaseTask作为哈希表中的密钥。所以代码需要像这样改变

function groupBy(array, col, col2, value) {
  var r = [],
    o = {};
  array.forEach(function(a) {
    // key is not 'Phase' only, it should combine 'Phase' and 'Task', others are the same.
    if (!o[a[col] + a[col2]]) {
      o[a[col] + a[col2]] = {};
      o[a[col] + a[col2]][col] = a[col];
      o[a[col] + a[col2]][col2] = a[col2];
      o[a[col] + a[col2]][value] = 0;
      r.push(o[a[col] + a[col2]]);

    }
    o[a[col] + a[col2]][value] += +a[value];
  });
  return r;
};

查看here