如果日期相等,则合并数组中的对象
我在 Javascript 中有一个数组,如果对象具有相同的提醒,我需要组合它们。
const tasks = [
{
id: 1,
title: "call Tom",
reminders: {
date: "2022-02-01",
time: "09:30"
}
},
{
id: 2,
title: "Meet Bred",
reminders: {
date: "2022-02-01",
time: "10:30"
}
},
{
id: 3,
title: "Mail Susan",
reminders: {
date: "2022-03-01",
time: "19:00"
}
},
输出应该是这样的
const combinedTasks = [
{
id: 1,
tasks: ["call Tom", "Meet Bred"],
reminders: {
date: "2022-02-01",
time: "09:30"
}
},
{
id: 3,
tasks: ["Mail Susan"]
reminders: {
date: "2022-03-01",
time: "19:00"
}
}
我想我需要使用 Array.reduce 方法,但我不知道如何正确地做到这一点
I have an array in Javascript and I need to combine objects if they have equal reminder.date
const tasks = [
{
id: 1,
title: "call Tom",
reminders: {
date: "2022-02-01",
time: "09:30"
}
},
{
id: 2,
title: "Meet Bred",
reminders: {
date: "2022-02-01",
time: "10:30"
}
},
{
id: 3,
title: "Mail Susan",
reminders: {
date: "2022-03-01",
time: "19:00"
}
},
Output should be like this
const combinedTasks = [
{
id: 1,
tasks: ["call Tom", "Meet Bred"],
reminders: {
date: "2022-02-01",
time: "09:30"
}
},
{
id: 3,
tasks: ["Mail Susan"]
reminders: {
date: "2022-03-01",
time: "19:00"
}
}
I suppose that I need to use Array.reduce method but I dont have idea hot to do it correctly
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是使用
reduce()
实现此目的的一种方法Here is one way you can accomplish this using
reduce()
尝试这个解决方案,它有效。
该代码的输出符合预期。
我希望这有帮助。
Try this solution , it works .
Output of this code is as expected .
I hope this is helpful .
你是对的,你必须使用
reduce
方法。用它来循环初始数组。因此,对于每个任务,您可以在未来数组中查看当前任务日期是否有任务。否则,您可以创建一个新任务并稍后添加下一个任务。
you are right, you have to use the
reduce
method.Use it to loop over your initial array. So for each task, you can watch in your futur array if you have a task at the current task date. Else you can create a new task and add next tasks later.
我希望这个方法对你有帮助。
I hope this approach would help you.