Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Combine objetos en una matriz si las fechas son iguales javascript

Tengo una matriz en Javascript y necesito combinar objetos si tienen el mismo recordatorio.fecha

 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" } },

La salida debería ser así

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

Supongo que necesito usar el método Array.reduce pero no tengo idea de cómo hacerlo correctamente

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Aquí hay una forma en que puede lograr esto usando 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);

about 4 years ago · Juan Pablo Isaza Relatório

0

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); } } })

Pruebe esta solución, funciona.

 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' } } ]

La salida de este código es la esperada. Espero que esto sea útil .

about 4 years ago · Juan Pablo Isaza Relatório

0

tienes razón, tienes que usar el método de reduce .

Úselo para recorrer su matriz inicial. Entonces, para cada tarea, puede ver en su matriz futura si tiene una tarea en la fecha de la tarea actual. De lo contrario, puede crear una nueva tarea y agregar las siguientes tareas más tarde.

 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);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda