0

as the title said, I need to push array of objects inside grouped objects. I found example here and it goes:

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>');

my result is:

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

What I want to get is that inside my grouped object is array of objects with properties: Task and Value (for each task I want value).

I tried this:

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;
};

and add "Task" parameter but only I got was:

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

Thanks for help!

1 Answer 1

1

You are using Phase and Task for the key in hash table. So the code need to be changed like this

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;
};

Check out here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.