7

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';
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
erosman
  • 7,094
  • 7
  • 27
  • 46
  • 1
    "*Of course I can declare the array element as a variable*". No, you can't, unless you use computed property names, introduced by ECMAScript 6. Your second code will produce the key `"arr"`, not `"b"`. – Oriol Feb 25 '15 at 13:48
  • @Oriol .. You are right... thank you ... I updated & corrected my post :) – erosman Feb 25 '15 at 13:58
  • 1
    Goodness, that data structure is mighty confusing – race_carr Feb 26 '15 at 01:48

2 Answers2

8

{ 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';
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
5

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Thank you dfsq. I updated my post with more info. I am actually coding scripts for Firefox, However, to be more compatible, I stay with ES5 for the time being. ;) Good to know though for when I am coding a Firefox addon. – erosman Feb 25 '15 at 14:08
  • I then stand partially corrected :) – mplungjan Feb 25 '15 at 14:31
  • In ES5, you can do: `Object.defineProperty({},array[1],{value:'good',enumerable:true})`. That might not be considered an improvement. – rici Feb 27 '15 at 01:26