[英]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 现在,如果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
}
]
}
]
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 我正在遍历所有对象,如果id相同,那么我将使用合并后的值创建一个新的对象,我觉得有些阐述
Can i achieve this through underscore js in a more abstract way? 我可以通过下划线js以更抽象的方式实现此目标吗?
_.groupBy
will do what you want, then use pick
/ omit
to map
the groups to the nested objects as you want them: _.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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.