gpt4 book ai didi

javascript - 如何对对象数组进行分组?

转载 作者:行者123 更新时间:2023-11-30 13:52:56 26 4
gpt4 key购买 nike

我有一个对象数组,例如:

const array = [
{
date: '02-02-1994',
time: '18:00',
services: {
first: 1,
second: 1
}
},
{
date: '02-02-1994',
time: '20:00',
services: {
first: 1,
second: 1
}
},
{
date: '02-04-1994',
time: '19:00',
services: {
first: 1,
second: 1
}
},
{
date: '02-04-1994',
time: '19:00',
services: {
first: 1,
second: 2
}
}
]

我想按时间和日期对它进行分组并得到结果数组:

const result = [{
date: '02-02-1994',
time: '18:00',
services: {
first: 1,
second: 1
}
},
{
date: '02-02-1994',
time: '20:00',
services: {
first: 1,
second: 1
}
},
{
date: '02-04-1994',
time: '19:00',
services: {
first: 2,
second: 3
}
}]

我想按日期对数组进行分组,然后按时间对数组进行分组,并在服务对象中求和。我尝试使用 reduce 按日期分组,但我不知道

最佳答案

您可以使用 reduce()方法。

const array = [{ date: '02-02-1994', time: '18:00', services: { first: 1, second: 1 } }, { date: '02-02-1994', time: '20:00', services: { first: 1, second: 1 } }, { date: '02-04-1994', time: '19:00', services: { first: 1, second: 1 } }, { date: '02-04-1994', time: '19:00', services: { first: 1, second: 2 } } ];

let result = array.reduce((arr, currentValue) => {

let item = arr.find(item =>
item.date === currentValue.date &&
item.time === currentValue.time);

if (item) {
item.services.first += currentValue.services.first;
item.services.second += currentValue.services.second;
} else {
arr.push(currentValue);
}

return arr;
}, []);

console.log(result);

关于javascript - 如何对对象数组进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com