Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 Respuestas
Responde la pregunta

0

try like this,

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda