Underscorejs:如何通过组合两个对象的值来创建新对象?

时间:2014-05-20 02:28:34

标签: javascript jquery underscore.js

我遇到了以下情况

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

现在,如果id相同,我需要以下列形式组合相同的对象值

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

        ]

我循环遍历所有对象,如果id是相同的,我正在创建一个具有组合值的新对象,我觉得有点详细说明

我可以通过下划线js 以更抽象的方式实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

_.groupBy会执行您想要的操作,然后根据需要将pick / omit map组用于嵌套对象:

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