Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

46
Vistas
How to combine two arrays into an array of objects?

I have two lists,

l1= ["apple","banana","grape"]
l2 = ["red","yellow","black"]

How to make a list of this type? (a list of objects)

l3 = [
   {fruit:"apple",colour:"red"},
   {fruit:"banana",colour:"yellow"},
   {fruit:"grape",colour:"balack"}
]

I tried something like this, but the output is not what I expected:

let l3 = [];
let Obj = {};
for (let l = 0;l<l1.length;l++) {
    Obj = {};
    for (h=0;h<l2.length;h++) {
        Obj["fruit"] = l1[h];
        Obj["colour"] = l2[h];
    }
    l3.push(Obj);
}
return l3;
7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You only need one loop, not nested loops.

for (let i = 0; i < l1.length; i++) {
    l3.push({fruit: l1[i], colour: l2[i]});
}
7 months ago · Juan Pablo Isaza Denunciar

0

You can use .map.

const l1 = ["apple", "banana", "grape"];
const l2 = ["red", "yellow", "black"];
const l3 = l1.map((fruit, index) => ({ fruit, color: l2[index] }));

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.