如何基于相同的值合并对象数组?

时间:2019-06-04 19:23:40

标签: javascript arrays

我有以下对象数组:

var array = [{
    country: "Austria",
    name: "2019-01-04T23:00:00.000Z",
    value: "1"
  },
  {
    country: "Austria",
    name: "2019-01-11T23:00:00.000Z",
    value: "3"
  },
  {
    country: "Austria",
    name: "2019-01-18T23:00:00.000Z",
    value: "1"
  }
]

我想操纵它来达到这个结果:

var array = [{
  country: "Austria",
  series: [{
      name: "2019-01-04T23:00:00.000Z",
      value: "1"
    },
    {
      name: "2019-01-11T23:00:00.000Z",
      value: "3"
    },
    {
      name: "2019-01-18T23:00:00.000Z",
      value: "1"
    }
  ]
}]

我读了很多问题,但没有一个帮助我。

4 个答案:

答案 0 :(得分:1)

这应该做:

var map = {};

for(var entity of array) {
    if(!map[entity.country]) {
        map[entity.country] = {
            country: entity.country,
            series: [
                {
                    name: entity.name,
                    value: entity.value
                }
            ]
        };
    }
    else {
        map[entity.country].series.push({
            name: entity.name,
            value: entity.value            
        });
    }
}

var mappedArray = Object.values(map);

答案 1 :(得分:1)

这是不带for循环和可变变量的功能解决方案:

.drop

答案 2 :(得分:1)

您可以循环遍历数组。使用destructuring分别获得属性countryrest。将每个唯一的country添加到group对象作为键,并将rest对象推到series数组。然后使用Object.values()将值作为数组获取

const array=[{country:"Austria",name:"2019-01-04T23:00:00.000Z",value:"1"},{country:"Austria",name:"2019-01-11T23:00:00.000Z",value:"3"},{country:"Austria",name:"2019-01-18T23:00:00.000Z",value:"1"}];

const group = {};

array.forEach(({ country, ...rest }) => {
  group[country] = group[country] || { country, series: [] };
  group[country].series.push(rest)
})

console.log(Object.values(group))

答案 3 :(得分:0)

您可以执行以下操作:

const result = array
    .map(
        c => ({
            country: c.country,
            series: array
                .filter(d => d.country === c.country)
                .map(
                    d => ({
                        name: d.name,
                        value: d.value
                    })
                )
        })
    )