I am trying to set an array element as an object Property
Simplified example:
var array = ['a', 'b', 'c'];
var obj = { array[1]: 'good' }
Above causes an error.
Update: In fact, I am passing the object as a part of another array ie a simplified example would be:
aObj[value] = ['one', {array[1]: 'good'}, 'two', 'three', 'four'];
Setting the obj[array[1]] = 'good';
style would mean using
aObj[value][1][array[1]] = 'good';
{ array[1]: 'good' }
throws an error because, when you use the Object literal notation in JavaScript, it treats the string before :
as the identifier and a valid identifier name cannot have [
or ]
in it.
So, use the []
notation, which allows any string to be used as the property name, like this
var array = ['a', 'b', 'c'];
var obj = {};
obj[array[1]] = 'good';
Maybe it's time to start giving ES6 answers too. In ECMAScript6 you can use expressions as object keys:
var array = ['a', 'b', 'c'];
var obj = {
[array[1]]: 'good'
}
In fact, this syntax is already supported in Firefox.
Currently the only way to use variable is to use bracket notation as described in other answer.
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