Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
¿Por qué mi código js omite la primera línea de la matriz al hacer un bucle?

quiero hacer un objeto desde una matriz 2D y la salida solo así

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

este es mi codigo

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

¿Qué tiene de malo este código? ¿Por qué se salta la primera línea de la matriz al hacer un bucle?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Debe devolver una matriz de objetos, no un solo objeto que sobrescriba en el bucle.

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

También puedes simplificarlo usando 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 Report

0

Está sobrescribiendo la propiedad dentro del objeto,

verifique el fragmento de código a continuación

 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 Report

0

Está sobrescribiendo los valores de z.firstName , z.lastName y z.gender durante su segundo ciclo, un objeto no puede contener valores duplicados

Debería considerar definir z como una matriz y usar el método array.push() .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!