On the second example you are creating kv2
as an object
with an unique property
named f
.
var f = 'abc';
var r = 'moon';
var kv2 = {
f: r,
};
console.log(kv2);
console.log(kv2.f);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
The new ECMAScript (ES6
) includes a feature named computed property names that will be adequate for what you are trying to do, i.e, use a property name stored in some variable. Example:
var f = 'abc';
var r = 'moon';
var kv2 = {
[f]: r, // Using computed property name!
};
console.log(kv2);
console.log(kv2[f]);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
However, and from wikipedia
, you can see this feature isn't available for you:
Apps Script is a scripting language for light-weight application development in the G Suite platform. It is based on JavaScript 1.6
with some portions of 1.7
and 1.8
and provides subset of ECMAScript 5 API.
So, the best you can do, if you still want to use a property name stored in a variable, is this:
var f = 'abc';
var r = 'moon';
var kv2 = {};
kv2[f] = r;
console.log(kv2);
console.log(kv2[f]);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}