简体   繁体   中英

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?

_.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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM