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

147
Vistas
Why my js code skip the first line of array when looping?

i want do make object from 2D array and the output only like this

{ firstName: 'd', lastName: 'e', gender: 'f' }

this is my code

function x(y) {
  var z = {}

  for (a = 0; a < y.length; a++) {
    z.firstName = y[a][0]
    z.lastName = y[a][1]
    z.gender = y[a][2]
  }
  return z
}

var y = [
  ["a", "b", "c"],
  ["d", "e", "f"]
]
console.log(x(y))

what's wrong with this code? why it skip the first line of array when looping?

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

0

You need to return an array of objects, not a single object that you keep overwriting in the loop.

function x(y) {
  var result = [];

  for (let a = 0; a < y.length; a++) {
    let z = {};
    z.firstName = y[a][0];
    z.lastName = y[a][1];
    z.gender = y[a][2];
    result.push(z);
  }
  return result;
}

var y = [
  ["a", "b", "c"],
  ["d", "e", "f"]
]
console.log(x(y))

You can also simplify it using map().

function x(y) {
  return y.map(i => ({
    firstName: i[0],
    lastName: i[1],
    gender: i[2]
  }));
}

var y = [
  ["a", "b", "c"],
  ["d", "e", "f"]
]
console.log(x(y))

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are overwriting the property inside the object,

check the code snippet below

function x(y) {
  const z = []
  
  for (let a = 0; a < y.length; a++) {
    z.push({
       firstName:y[a][0],
       lastName:y[a][1],
       gender:y[a][2],
    })
    
  }
  return z
}

var y = [
  ["a", "b", "c"],
  ["d", "e", "f"]
]
console.log(x(y))

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are overwriting the values of z.firstName, z.lastName and z.gender during your second loop, an object may not contain duplicate values

You should consider defining z as an array and using the array.push() method.

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