0

I've created this list by grouping elements from another list (with d3.nest)

array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3},
                               {Id: "1234b", ECTS: 3}]}, 
          {key: "7S", values: [{Id: "1534a", ECTS: 5},
                               {Id: "154b", ECTS: 4},]} ]

From this list I want to create something like this:

array = [{key: "6S", values: { 3: [{Id: "1234a"}, {Id: "1234b"}]}},

        {key: "7S", values: { 5: [{Id: "1534a"}], 4: [{Id:"1534a"}]}}]

Actually I want to group the data for each key (6S, 7S) by ECTS. I've tried with _.groupBy.... but is not working. The problem is that the elements that I want to group are objects, already grouped once. Any idea about how I could group the items?

2 Answers 2

1

You can try following

var array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]},  {key: "7S", values: [{Id: "1534a", ECTS: 5}, {Id: "154b", ECTS: 4},]} ];


 array.forEach((obj) => {
    var values = {};
    // Iterate over array and create the updated value
    obj.values.forEach((item) => {
       values[item.ECTS] = values[item.ECTS] || [];
       values[item.ECTS].push({"Id" : item.Id});
    });
    // Set the updated value in object
    obj.values = values;

});
                  
console.log(array);

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

Comments

0

var array = [{
        key: "6S",
        values: [{
                Id: "1234a",
                ECTS: 3
            },
            {
                Id: "1234b",
                ECTS: 3
            }
        ]
    },

    {
        key: "7S",
        values: [{
                Id: "1534a",
                ECTS: 5
            },
            {
                Id: "154b",
                ECTS: 4
            },
        ]
    }
]

array = array.map(function(v1) {
    var updatedVal = v1.values.reduce(function(obj, v2) {
        obj[v2.ECTS] = obj[v2.ECTS] || [];
        obj[v2.ECTS].push({
            Id: v2.Id
        });
        return obj;
    }, {});
    v1.values = updatedVal;
    return v1;
});

console.log(array);

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.