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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With