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

kevin godfrey
  • 153
  • 1
  • 11

2 Answers2

1

try like this,

(function(){{ r: 'world' }
var r = "Hello"
var ob = {[r]:"world"}
console.log(ob);
})();
Dev-2019
  • 547
  • 3
  • 11
1

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" }
FZs
  • 16,581
  • 13
  • 41
  • 50