Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
Array separate odd and even to array of objects Javascript

I have a question.

I have a Array like below

WorkList1 = ["Monday", "running", "Tuesday", "swimming", "Wednesday", "riding"]

I expect change it like

WorkList2 = [{ "day": "Monday", "exercise": "running" }, 
             { "day": "Tuesday", "exercise": "swimming" },
             { "day": "Wednesday", "exercise": "riding" }]

but it seems got some Error, this is my code.

const WorkList2 = [];
const object = { "day": '', "exercise": '' };
for (let i = 0; i < WorkList1.length; i += 1) {
  if (i % 2 === 0) {
    object['day'] = i;
  } else {
    object['exercise'] = i;
  }
  WorkList2.push(object);
}

I have read some thread about Array but I still have some trouble..... Could somebody help me to figure it out? thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

1) You are assigning the value as array index i

object['day'] = i; 

2) It will have as many objects as there are in WorkList1.

You have to skip the insertion at every odd index. What you can do is just loop over the array and increment it by 2 instead of 1 and push data value as WorkList1[i] and exercise as WorkList1[i + 1]

const WorkList1 = [
  "Monday",
  "running",
  "Tuesday",
  "swimming",
  "Wednesday",
  "riding",
];

const WorkList2 = [];

for (let i = 0; i < WorkList1.length; i += 2) {
  WorkList2.push({
    day: WorkList1[i],
    exercise: WorkList1[i + 1],
  });
}

console.log(WorkList2);

You can also try the second solution

const WorkList1 = [
  "Monday",
  "running",
  "Tuesday",
  "swimming",
  "Wednesday",
  "riding",
];

const WorkList2 = [];

for (let i = 0; i < WorkList1.length; i += 1) {
  if (i % 2 === 0) {
    WorkList2.push({
      day: WorkList1[i]
    });
  } else {
    const lastObj = WorkList2[WorkList2.length - 1];
    lastObj.exercise = WorkList1[i];
  }
}

console.log(WorkList2);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda