如何将多个对象与单个对象同名/组合(嵌套)

时间:2018-01-25 07:14:24

标签: javascript json node.js underscore.js lodash

我将学生及其在各种科目中的分数数据作为一系列对象。当两个对象的名称相同时,我需要将数据作为单个对象进行分组,这样我每个学生只能有一条记录。示例数据的示例:

{
    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这样的库来实现这一点。

1 个答案:

答案 0 :(得分:1)

你可以使用mapreduce来做这样的事情:



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;
&#13;
&#13;