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

108
Views
¿Cómo hacer un bucle de una matriz de objetos sin índice como campo en Javascript?

Tengo que organizar una lista de pedidos, luego de tener los datos listos, esta lista de objetos debe insertarse en otro objeto.

Creé un código simplificado para una mejor comprensión:

 const orderList = []; orderList.push({ order1: { desc: "smt1" } }) orderList.push({ order2: { desc: "smt2" } }) const result = { anotherVar1: 1, anotherVar2: 2, ...orderList } console.log("result", result)

Producción
 { '0': { order1: { desc: 'smt1' } }, '1': { order2: { desc: 'smt2' } }, anotherVar1: 1, anotherVar2: 2, }
Salida deseada:
 { order1: { desc: 'smt1' }, order2: { desc: 'smt2' }, anotherVar1: 1, anotherVar2: 2, }

¿Cómo lograr el resultado deseado?

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

0

Desea que orderList sea un objeto, no una matriz. Luego, en lugar de usar push , desea establecer la clave/valor en el objeto.

 const orderList = {}; orderList.order1 = { desc: "smt1" }; orderList.order2 = { desc: "smt2" }; const result = { anotherVar1: 1, anotherVar2: 2, ...orderList } console.log('result', result);

about 4 years ago · Juan Pablo Isaza Report

0

Como @Rocket Hazmat menciona en su respuesta , use un objeto en lugar de una matriz


Para responder a la pregunta original, deberá convertir la matriz de objetos en un objeto antes de poder 'fusionarlos'

 const orderList = []; orderList.push({ order1: { desc: "smt1" } }); orderList.push({ order2: { desc: "smt2" } }); const result = { anotherVar1: 1, anotherVar2: 2, ...Object.assign({}, ...orderList) }; console.log('result', result);

Cómo convertir una matriz de objetos en objetos con pares de valores clave

about 4 years ago · Juan Pablo Isaza Report

0

Como mejor método, mantenga esa matriz como un objeto para que pueda evitar la duplicación y el bucle adicional

Y como en su mismo método, puede seguir este código para hacer el resultado deseado

 const orderList = []; orderList.push({ order1: { desc: "smt1" } }) orderList.push({ order2: { desc: "smt2" } }) const result = { anotherVar1: 1, anotherVar2: 2, } orderList.map(d => { for(key in d) { result[key] = d[key] } }) console.log("result", result)

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!