【问题标题】:How can I Club/Combine multiple objects with same name as single object (Nesting)如何将多个具有相同名称的对象合并为单个对象(嵌套)
【发布时间】:2018-01-25 07:14:24
【问题描述】:

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

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

【问题讨论】:

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


【解决方案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)

【讨论】:

  • 这只是返回与我的输入相同
  • @GopiNath 哎呀!我的错!虽然我已经根据你的问题更新了我的答案。
  • @GopiNath 如果答案对您有用,如此处所示,请考虑接受/支持它。 :)
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多