Pawan Kalyan
Pawan Kalyan

Reputation: 581

Underscorejs:How to create a new object by combining values from two objects?

I came across the following scenario

var obj1= [
          {
            "id": 97,
            "name": "Sample1",
            "classId": 751,
            "gradeId": 1,
            "studentId": 1
          },
          {
            "id": 98,
            "name": "Sample2",
            "classId": 751,
            "gradeId": 1,
            "studentId": 2
          },
          {
            "id": 97,
            "name": "Sample1",
            "classId": 751,
            "gradeId": 2,
            "studentId": 3
          },
          {
            "id": 98,
            "name": "Sample2",
            "classId": 751,
            "gradeId": 2,
            "studentId": 4
          }
        ]

Now ,If the id's are same,I need to combine the identical object values in the following form

var obj2=[
        {
            "id": 97,
            "name": "Sample1",
            "classId": 751,
            "rating":[
            {
            "gradeId": 1,
            "studentId": 1
            }
            {
            "gradeId": 2,
            "studentId": 3
            }
            ]
          },
           {
            "id": 98,
            "name": "Sample2",
            "classId": 751,
            "rating":[
            {
            "gradeId": 1,
            "studentId": 2
            }
            {
            "gradeId": 2,
            "studentId": 4
            }
            ]
          }

        ]

I am looping through all the objects and ifnthe id's are same I am creating a new object with the combined values,which i feel a little bit elaborated

Can i achieve this through underscore js in a more abstract way?

Upvotes: 0

Views: 64

Answers (1)

Bergi
Bergi

Reputation: 664548

_.groupBy will do what you want, then use pick/omit to map the groups to the nested objects as you want them:

var obj2 = _.map(_.groupBy(obj1, "id"), function(group) {
    var o = _.omit(group[0], "gradeId", "studentId");
    o.rating = _.map(group, function(s) {
        return _.pick(s, "gradeId", "studentId");
    });
    return o;
});

Upvotes: 1

Related Questions