[英]how to transform array of object in JavaScript?
I need to transform array of objects in a way that an object with same service stores all the total_costs in a single array.我需要以具有相同服务的对象将所有 total_costs 存储在单个数组中的方式转换对象数组。
So array of objects, each object contains array of total_costs with same service So, from:所以对象数组,每个对象包含具有相同服务的 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' } ]
Into:进入:
[
{
"service": "136981853693",
"total_costs" : [8.7002453728, 105.6087751695, 121.3059868476...]
},
{
"service": "136981853692",
"total_costs" : [263.6372995531]
}
]
How can I do it?我该怎么做?
Use reduce
to group into an object indexed by the service
property, and then get that object's values:使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.