我将学生及其在各种科目中的分数数据作为一系列对象。当两个对象的名称相同时,我需要将数据作为单个对象进行分组,这样我每个学生只能有一条记录。示例数据的示例:
{
data: [{
"name: xxx,
"createdDate:10/01/2018,
subj1: 20,
subj2: 40
},
{
"name: xxx,
"createdDate:10/11/2017,
subj1: 40,
subj2: 70
},
{
"name: yyy,
"createdDate:10/01/2018,
subj1: 20,
subj2: 40
}]
}
我需要将它转换成这样的东西:
{
data: [
{
name: xxx,
subj1: [20, 40],
subj2: [70, 40]
},
{
name: yyy,
subj1: [20],
subj2: [40]
}
]
}
我如何在node js
中实现这一目标。只有通过循环,我可以做或者有一个简单的方法,我可以通过使用像lodash,下划线js这样的库来实现这一点。
答案 0 :(得分:1)
let sampleData = {
data:[{
name: "xxx",
createdDate:10/01/2018,
subj1:20,
subj2:40
},
{
name: "xxx",
createdDate:10/11/2017,
subj1:40,
subj2:70
},
{
name: "yyy",
createdDate:10/01/2018,
subj1:20,
subj2:40
}]
};
let sorted = sampleData.data.sort((element1, element2) => {
return element1.name <= element2.name ? -1 : 1
}).reduce((accumulator, currentValue, currentIndex, array) => {
if (accumulator.data.length == 0){
accumulator.data.push({name:currentValue.name, subj1:[currentValue.subj1], subj2:[currentValue.subj2]});
return accumulator;
} else {
if (accumulator.data[accumulator.data.length - 1].name == currentValue.name){
accumulator.data[accumulator.data.length - 1].subj1.push(currentValue.subj1);
accumulator.data[accumulator.data.length - 1].subj2.push(currentValue.subj2);
} else {
accumulator.data.push({name:currentValue.name, subj1:[currentValue.subj1], subj2:[currentValue.subj2]});
}
return accumulator;
}
}, {data:[]})
console.log(sorted)
&#13;