Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an Array Element as an Object Property [duplicate]

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';
like image 380
erosman Avatar asked Feb 25 '15 13:02

erosman


2 Answers

{ 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';
like image 84
thefourtheye Avatar answered Sep 21 '22 04:09

thefourtheye


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.

like image 29
dfsq Avatar answered Sep 23 '22 04:09

dfsq