Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

try like this,

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading