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

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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