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

171
Views
Cómo agregar correctamente una matriz de elementos a una matriz de objetos

Tengo esta matriz y matriz de objetos en mi código React:

 var A = [ {id: 1, name: "han"}, {id: 2, name: "mohd"}, ] var B = [100, 200];

y quiero agregar B a A, para que la salida sea algo como esto:

 var A = [ {id: 1, name: "han", score: "100"}, {id: 2, name: "mohd", score: "200}, ]

Intenté hacerlo con el siguiente código:

 var newArray = []; for (let k = 0; k < A.length; k++) { newArray = B.map(score => ({...A[k], score})); } return newArray;

Sin embargo, el código anterior devuelve este resultado cuando se registra en la consola:

 newArray = [ {id: 2, name: "mohd", score: "100"}, {id: 2, name: "mohd", score: "200}, ]

Solo agrega los elementos al último objeto, en lugar de a todos los objetos. Alguien sabe lo que está mal con mi código? ¡Gracias!

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

0

Si va a usar el map , tampoco necesita un bucle, ya que el map iterará sobre la matriz de objetos y devolverá una nueva matriz con nuevos objetos que contengan la propiedad de score .

Use el segundo parámetro de la devolución de llamada, el índice , para identificar qué elemento de b debemos agregar como puntaje.

 const a = [ {id: 1, name: 'han'}, {id: 2, name: 'mohd'}, ]; const b = [100, 200]; // `map` over `a` making sure we get the object // in each iteration as well as its index const out = a.map((obj, i) => { // Create a new object adding in the // new `score` property using the element in `b` // that matches the index return { ...obj, score: b[i] }; }); console.log(out);

about 4 years ago · Juan Pablo Isaza Report

0

Prueba algo como esto

 const C = A.map((value, idx) =>({ ...value, score: B[idx], })); console.log(C)
about 4 years ago · Juan Pablo Isaza Report

0

Si la longitud de ambos arreglos será la misma, use este método

 var A = [ {id: 1, name: "han"}, {id: 2, name: "mohd"}, ] var B = [100, 200]; console.log(A.map((x,i)=> {return { ...x, score:B[i] } } ))

Si no está seguro de usar esto, por ejemplo.

 var A = [ {id: 1, name: "han"}, {id: 2, name: "mohd"}, {id: 2, name: "mohd"}, ] var B = [100, 200]; console.log(A.map((x,i)=> {return { ...x, score:!B[i]?0:B[i] } } ))
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!