我如何 Club/Combine 与单个对象同名的多个对象(嵌套)

How can I Club/Combine multiple objects with same name as single object (Nesting)

我有一个学生数据和他们在各个科目中的分数作为对象数组。当两个对象的名称相同时,我需要将数据合并为一个对象,以便每个学生只有一个记录。示例数据示例:

{
    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、underscore js 这样的库来实现。

您可以使用 map and reduce 做这样的事情:

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)