Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define object field name based on variable value in javascript [duplicate]

Tags:

javascript

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?

like image 933
Rafael Lima Avatar asked Sep 21 '25 08:09

Rafael Lima


1 Answers

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

like image 63
Ran Turner Avatar answered Sep 22 '25 22:09

Ran Turner