Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
javascript push key value into object with index

I have a object variable and i want to push into my object a new { key: "value" } but with a loop and using loop index.

Something like this:

    let headers = {
        product_title: "Product Name",
        action: "Status",
        quantity: "Quantity",
        priority: "Priority",
    };

    for (let i = 0; i < bigger; i++) {
        headers = { ...headers, ...{ 'org_{i}': i } };
    }

is there a way to do something like this or add unique key with indexes?

Finally i need something like below:

let headers = {
   ...old data
   key_1: "",
   key_2: "",
   key_3: "",
};
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

There's an ES6 thing called "computed properties" which allows regular JS enclosed in [] to form a string key...

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)

Neat, but this creates a throw-away object for each iteration. Skipping the literal with the spread, you can use older JS, more efficiently...

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 Relatório

0

To add new key-value into object you can literally just use

headers[key] = value

But if you are intending to set keys dynamically I suggest you to check this out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

about 4 years ago · Juan Pablo Isaza Relatório

0

Try something like below

const output = [...Array(bigger)].reduce((acc, curr, index) => {
    return ({ ...headers, ...acc, [`org_${index}`]: index })
}, {});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda