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

257
Views
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 answers
Answer question

0

try like this,

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

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 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!