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';
3
  • 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". Commented Feb 25, 2015 at 13:48
  • @Oriol .. You are right... thank you ... I updated & corrected my post :) Commented Feb 25, 2015 at 13:58
  • 1
    Goodness, that data structure is mighty confusing Commented Feb 26, 2015 at 1:48

2 Answers 2

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';
Sign up to request clarification or add additional context in comments.

2 Comments

Also it cannot be a variable before the :
Seems in ES6 you may have an expression before the : as mentioned by @dfsq
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.

3 Comments

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.
I then stand partially corrected :)
In ES5, you can do: Object.defineProperty({},array[1],{value:'good',enumerable:true}). That might not be considered an improvement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.