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

87
Views
Javascript empuja el valor de la clave en el objeto con índice

Tengo una variable de objeto y quiero insertar en mi objeto una nueva { key: "value" } pero con un bucle y usando un índice de bucle.

Algo como esto:

 let headers = { product_title: "Product Name", action: "Status", quantity: "Quantity", priority: "Priority", }; for (let i = 0; i < bigger; i++) { headers = { ...headers, ...{ 'org_{i}': i } }; }

¿Hay alguna manera de hacer algo como esto o agregar una clave única con índices?

Finalmente necesito algo como a continuación:

 let headers = { ...old data key_1: "", key_2: "", key_3: "", };
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Hay una cosa de ES6 llamada "propiedades calculadas" que permite que JS regular entre [] forme una clave de cadena ...

 let headers = { product_title: "Product Name", action: "Status", quantity: "Quantity", priority: "Priority", }; for (let i = 0; i < 5; i++) { headers = { ...headers, ['key_' + i]: i } } console.log(headers)

Genial, pero esto crea un objeto desechable para cada iteración. Saltándose el literal con la extensión, puede usar JS más antiguo, de manera más eficiente ...

 let headers = { product_title: "Product Name", action: "Status", quantity: "Quantity", priority: "Priority", }; for (let i = 0; i < 5; i++) { headers['key_' + i] = i } console.log(headers)

about 4 years ago · Juan Pablo Isaza Report

0

Para agregar una nueva clave-valor en el objeto, literalmente puede usar

 headers[key] = value

Pero si tiene la intención de establecer claves dinámicamente, le sugiero que consulte esto https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

about 4 years ago · Juan Pablo Isaza Report

0

Prueba algo como a continuación

 const output = [...Array(bigger)].reduce((acc, curr, index) => { return ({ ...headers, ...acc, [`org_${index}`]: index }) }, {});
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!