4

Is possible in javascript define an object field name based on the value of a variable INLINE?

for exemple:

const field = "name";

const js = {field:"rafael"};

console.log(js);

the result of this code will be {field:rafael} but the result I want is {name:rafael}.

I know I can do

const field = "name";

const js = {};
js[field] = "rafael";

but i would like to do inline as I initialize the object. Is that possible?

Andy
  • 61,948
  • 13
  • 68
  • 95
Rafael Lima
  • 3,079
  • 3
  • 41
  • 105

1 Answers1

4

The es6 version of JavaScript allows you to handle this issue, we can use variables while creating the object to dynamically set the property like so:

const field = "name";

const js = {[field] : "rafael"};

console.log(js);

Setting dynamic property keys - https://www.c-sharpcorner.com/blogs/how-to-set-dynamic-javascript-object-property-keys-with-es6

Ran Turner
  • 14,906
  • 5
  • 47
  • 53