如果日期相等,则合并数组中的对象

发布于 2025-01-09 12:22:08 字数 661 浏览 2 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

_蜘蛛 2025-01-16 12:22:08

这是使用 reduce() 实现此目的的一种方法

let 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"
    }
}];

let combinedTasks = tasks.reduce((combined, x) => {
    // Try to find an existing item in the combined tasks array where the date equals this task item.
    let match = combined.find(y => y.reminders.date == x.reminders.date);
    if (match) {
        // If we find a match, add this task item's title to the combined item's tasks array.
        match.tasks.push(x.title);
    } else {
        // If we didn't find a match, take this task item and turn it into a combined tasks item with a tasks array so that future items in the tasks array can be combined with this one.
        let copy = { ...x };
        copy.tasks = [x.title];
        delete copy.title;
        combined.push(copy);
    }
    return combined;
}, []);


console.log(combinedTasks);

Here is one way you can accomplish this using reduce()

let 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"
    }
}];

let combinedTasks = tasks.reduce((combined, x) => {
    // Try to find an existing item in the combined tasks array where the date equals this task item.
    let match = combined.find(y => y.reminders.date == x.reminders.date);
    if (match) {
        // If we find a match, add this task item's title to the combined item's tasks array.
        match.tasks.push(x.title);
    } else {
        // If we didn't find a match, take this task item and turn it into a combined tasks item with a tasks array so that future items in the tasks array can be combined with this one.
        let copy = { ...x };
        copy.tasks = [x.title];
        delete copy.title;
        combined.push(copy);
    }
    return combined;
}, []);


console.log(combinedTasks);

很酷又爱笑 2025-01-16 12:22:08
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"
 }
}
]
tasks.sort((a,b)=>{
  return new Date(a.reminders.date) - new Date(b.reminders.date)
})

let output = [];
tasks.map((val,index)=>{
   if(index===0){
      let obj = {}
      temp = [];
      temp.push(val.title);
      obj.id = val.id;
      obj.tasks = [...temp];
      obj.reminders = {...val.reminders};
      output.push(obj);
   }else{
      if(output[output.length-1].reminders.date===val.reminders.date){
         output[output.length-1].tasks.push(val.title);
      }else{
          let obj = {}
          temp = [];
          temp.push(val.title);
          obj.id = val.id;
          obj.tasks = [...temp];
          obj.reminders = val.reminders;
          output.push(obj);
      }
   }
})

尝试这个解决方案,它有效。

Output : 
[
  {
    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' }
  }
]

该代码的输出符合预期。
我希望这有帮助。

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"
 }
}
]
tasks.sort((a,b)=>{
  return new Date(a.reminders.date) - new Date(b.reminders.date)
})

let output = [];
tasks.map((val,index)=>{
   if(index===0){
      let obj = {}
      temp = [];
      temp.push(val.title);
      obj.id = val.id;
      obj.tasks = [...temp];
      obj.reminders = {...val.reminders};
      output.push(obj);
   }else{
      if(output[output.length-1].reminders.date===val.reminders.date){
         output[output.length-1].tasks.push(val.title);
      }else{
          let obj = {}
          temp = [];
          temp.push(val.title);
          obj.id = val.id;
          obj.tasks = [...temp];
          obj.reminders = val.reminders;
          output.push(obj);
      }
   }
})

Try this solution , it works .

Output : 
[
  {
    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' }
  }
]

Output of this code is as expected .
I hope this is helpful .

余生一个溪 2025-01-16 12:22:08

你是对的,你必须使用reduce方法。

用它来循环初始数组。因此,对于每个任务,您可以在未来数组中查看当前任务日期是否有任务。否则,您可以创建一个新任务并稍后添加下一个任务。

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 combinatedTasks = tasks.reduce((_combinatedTasks, currentTask) => {
    const currentDate = currentTask.reminders.date;
    const combinatedTaskAtCurrentDate = _combinatedTasks.find(task => task.reminders.date === currentDate);
    if (combinatedTaskAtCurrentDate) {
        combinatedTaskAtCurrentDate.tasks.push(currentTask.title);
    } else {
        _combinatedTasks.push({
            id: currentTask.id,
            tasks: [currentTask.title],
            reminders: currentTask.reminders
        });
    }
    return _combinatedTasks;
}, []);

console.log(combinatedTasks);

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.

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 combinatedTasks = tasks.reduce((_combinatedTasks, currentTask) => {
    const currentDate = currentTask.reminders.date;
    const combinatedTaskAtCurrentDate = _combinatedTasks.find(task => task.reminders.date === currentDate);
    if (combinatedTaskAtCurrentDate) {
        combinatedTaskAtCurrentDate.tasks.push(currentTask.title);
    } else {
        _combinatedTasks.push({
            id: currentTask.id,
            tasks: [currentTask.title],
            reminders: currentTask.reminders
        });
    }
    return _combinatedTasks;
}, []);

console.log(combinatedTasks);

临走之时 2025-01-16 12:22:08

我希望这个方法对你有帮助。

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"
 }
}];

let cmbArray =[];
tasks.forEach(x=>{
  if ( item = cmbArray.find(a=>a.reminders.date === x.reminders.date))  
  {
    item.tasks.push(x.title);    
  }
  else
  {
   x.tasks = [x.title];
   delete  x.title;
   cmbArray.push(x);
   }
});

  console.log(cmbArray);

I hope this approach would help you.

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"
 }
}];

let cmbArray =[];
tasks.forEach(x=>{
  if ( item = cmbArray.find(a=>a.reminders.date === x.reminders.date))  
  {
    item.tasks.push(x.title);    
  }
  else
  {
   x.tasks = [x.title];
   delete  x.title;
   cmbArray.push(x);
   }
});

  console.log(cmbArray);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文