如何转换对象数组?

时间:2018-06-08 01:28:28

标签: javascript

我需要以具有相同服务的对象将所有total_cost存储在单个数组中的方式转换对象数组。

所以对象数组,每个对象包含具有相同服务的total_costs数组 所以,来自:

[ 
     { total_costs: 263.6372995531,
       service: '136981853692',
       date_fields: '2018-04-02T00:00:00' },
     { total_costs: 121.3059868476,
       service: '136981853693',
       date_fields: '2018-04-16T00:00:00' },
     { total_costs: 105.6087751695,
       service: '136981853693',
       date_fields: '2018-04-23T00:00:00' },
     { total_costs: 8.7002453728,
       service: '136981853693',
       date_fields: '2018-04-30T00:00:00' } ]

分为:

 [
    {
      "service": "136981853693",
      "total_costs" : [8.7002453728, 105.6087751695, 121.3059868476...]
    },
    {
      "service": "136981853692",
      "total_costs" : [263.6372995531]
    }
  ]

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用reduce分组到由service属性索引的对象,然后获取该对象的值:

const input=[{total_costs:263.6372995531,service:'136981853692',date_fields:'2018-04-02T00:00:00'},{total_costs:121.3059868476,service:'136981853693',date_fields:'2018-04-16T00:00:00'},{total_costs:105.6087751695,service:'136981853693',date_fields:'2018-04-23T00:00:00'},{total_costs:8.7002453728,service:'136981853693',date_fields:'2018-04-30T00:00:00'}];

const output = Object.values(
  input.reduce((a, { total_costs, service }) => {
    if (!a[service]) a[service] = { service, total_costs: [] };
    a[service].total_costs.push(total_costs);
    return a;
  }, {})
);
console.log(output);