我有来自 API 的响应文本,如下所示,我想将它们聚合为新格式响应。但这是相当困难的,请帮助我(使用JavaScript)
API 的响应:
[
{
sumTime: "2024-04-25 12:00:00",
equipParaName: "P1",
sumValue: 5
},
{
sumTime: "2024-04-25 05:00:00",
equipParaName: "P2",
sumValue: 10,
},
{
sumTime: "2024-04-25 09:00:00",
equipParaName: "P1",
sumValue: 8
},
{
sumTime: "2024-04-25 08:00:00",
equipParaName: "P2",
sumValue: 3,
},
{
sumTime: "2024-04-25 08:00:00",
equipParaName: "P3",
sumValue: 12,
}
]
条件:
相同
sumTime
,equipParaName
不可重复
如果有3个唯一的
equipParaName
,则预期结果在一个对象中最多有3个属于它们的属性
相同
equipParaName
必须按sumTime
ASC排序
equipParaName: P1, sumTime: 2024-04-25 12:00:00, sumValue: 5
equipParaName: P1, sumTime: 2024-04-25 09:00:00, sumValue: 8
==> The sumTime 2024-04-25 09:00:00 should be added to 1st object and sumTime: 2024-04-25 12:00:00 added to 2nd object in result list
期待:
[
{
index: 1,
P1: 8,
P1_sumTime: "2024-04-25 09:00:00",
P2: 10,
P2_sumTime: "2024-04-25 05:00:00",
P3: 12,
P3_sumTime: "2024-04-25 07:00:00"
},
{
index: 2,
P1: 5,
P1_sumTime: "2024-04-25 12:00:00",
P2: 3,
P2_sumTime: "2024-04-25 08:00:00"
}
]
第一个暴力方法:
equipParaName
对相同
sumTime
equipParaName
const input=[{sumTime:"2024-04-25 12:00:00",equipParaName:"P1",sumValue:5},{sumTime:"2024-04-25 05:00:00",equipParaName:"P2",sumValue:10},{sumTime:"2024-04-25 09:00:00",equipParaName:"P1",sumValue:8},{sumTime:"2024-04-25 08:00:00",equipParaName:"P2",sumValue:3},{sumTime:"2024-04-25 08:00:00",equipParaName:"P3",sumValue:12}];
const ps = {};
for(let i=0;i<input.length;i++){
const item = input[i];
(ps[item.equipParaName] ??= []).push(i);
}
const sorted = [];
for(const [p, grp] of Object.entries(ps)){
const orig = grp.slice();
const idxs = grp.sort((a,b) => (a = input[a], b = input[b], a.sumTime > b.sumTime ? 1 : a.sumTime < b.sumTime ? -1 : 0));
for(let i=0;i<orig.length;i++){
sorted[orig[i]] = input[idxs[i]];
}
}
const slots = [];
for(const item of sorted){
const slot = slots.find(slot => !slot[item.equipParaName]);
if(slot) slot[item.equipParaName] = item;
else slots.push({[item.equipParaName]: item});
}
const result = slots.map((grp, i) => Object.entries(grp).reduce((r, [key, {sumValue, sumTime}]) => (r[key] = sumValue, r[key + '_sumTime'] = sumTime, r), {index:i+1}));
console.log(result);
.as-console-wrapper{
max-height:100% !important;
}