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

261
Visualizações
How can i use a variable's value as a key when i create a javascript object?
(function(){{ r: 'world' }
var r = "Hello"
var ob = {r:"world"}
console.log(ob);
})();

Outputs: { r: 'world' }

But I want the output to be {Hello:'world'}

Now it's kind of obvious as to why this is happening. javascript objects are meant to be created in key-value pairs. and the key can be directly written without wrapping the key in double quotes. and therefore the "r" here is being considered as the key name and not as a variable.

but I want to know whether we could use a variable's value as a key-name while defining a js object like this.

now I did try out a few things before I came here. which include

Tryout 1:

(function(){{ r: 'world' }
var r = "Hello" 
var ob = {`${r}`:"world"}
console.log(ob);
})();

This gives an error ie. SyntaxError: Unexpected template string

I'd appreciate it if someone can address this as well.

Tryout 2:

(function(){{ r: 'world' }
var r = "Hello" 
var ob = {}
ob[r] = "world"
console.log(ob); 
})();

Now this outputs { Hello: 'world' }

But then again this takes two lines, one to create an empty object and the second to create a property for it. and something just feels wrong about writing two lines for this!

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

0

try like this,

(function(){{ r: 'world' }
var r = "Hello"
var ob = {[r]:"world"}
console.log(ob);
})();
about 4 years ago · Juan Pablo Isaza Relatório

0

As of ES6, you can surround the property name with square brackets to do it:

var r = "Hello"
var ob = { [r]: "world" }
console.log(ob); //{ Hello: "world" }
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