1

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
  • 53,323
  • 11
  • 64
  • 89
Rafael Lima
  • 2,761
  • 30
  • 78

1 Answers1

0

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
  • 8,973
  • 3
  • 23
  • 37