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

150
Visualizações
Can I set Javascript object keys based on a variable, e.g index of a loop?

I'm looping over an array, getting data from an API on each iteration.

I want to pass data from all iterations of the loop from my express server to the browser using res.json(), so I want to create an object that contains an object of data for each API call, as well as some other key-value pairs that will be created depending on what is returned.

e.g.
on loop index 0:

artist0: 
     {
        data: 'data',
        moreData: 'more-data'
     }

on loop index 1:

artist1: 
     {
        data: 'data',
        moreData: 'more-data'
     }

etc

I would use an array, but one of the calls (at random) will result in another key value pair, e.g.:

correctAnswer: 'a_url.com' 

this will be generated by one of the earlier API calls at random, so I cant get it at the other end using its array index.

I need the key 'correctAnswer', so I also need each object of API data to be identified by which API call it came from.

Short question: Can I name keys based on variables?

As always, your kind help is greatly appreciated :-)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could solve this by not putting artists directly in the object, like this, using a array inside a single attribute of the object:

{
    "artists": [
        {
            "data": "data",
            "moreData": "more-data"
        },
        {
            "data": "data",
            "moreData": "more-data"
        }
    ],
    "correctAnswer": 3
}

Or alternatively, if you really want a dynamic key you can use

{
     [`artist${artistIndex}`]: {'data': 'data'}
}
about 4 years ago · Juan Pablo Isaza Relatório

0

This might help you

https://www.geeksforgeeks.org/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal/#:~:text=ES6%20defines%20'ComputedPropertyName'%20as%20part,an%20expression%20in%20square%20brackets.

"ES6 defines ‘ComputedPropertyName’ as part of the grammar for object literals, which helps use a variable for a key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets"

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