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

99
Views
Push in typescript está agregando el último objeto modificado en un bucle

Estoy tratando de crear una matriz a partir de un objeto modificado, pero el método Array<any>.push() siempre agrega el objeto que se modifica al final del ciclo. Aquí hay un código de muestra con el que estoy tratando de trabajar:

 let data: any = JSON.parse('{"messages":[{"id":"1234"},{"id":"2345"},{"id":"3456"}]}'); let myObject:any; let idMapping: any[] = []; for(let index = 0; index < 1; index++) { myObject = {DocID: "", index: index}; for (let val of data.messages) { myObject.DocID = val.id; // console.log("After update: ", myObject); // this gives me the correct object idMapping.push(myObject); } } console.log(idMapping) // array with same identical values, infact the last modified value in for loop

Esto me está dando una lista de los mismos objetos en comparación con lo que esperaba que fuera una lista de objetos que tienen un DocID diferente.

Soy nuevo en TypeScript y Nodejs, por lo que agradecería cualquier ayuda.

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

0

¡Usted modifica y agrega el mismo objeto a la matriz una y otra vez!

En su lugar, debe crear un nuevo objeto en cada iteración:

 let data: any = JSON.parse('{"messages":[{"id":"1234"},{"id":"2345"},{"id":"3456"}]}'); let idMapping: any[] = []; for(let index = 0; index < 1; index++) { for (let val of data.messages) { let myObject = {DocID: "", index: index}; myObject.DocID = val.id; // console.log("After update: ", myObject); // this gives me the correct object idMapping.push(myObject); } } console.log(idMapping)
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!