Setting an array element as an object property

I am trying to set an array element as a Property object

A simplified example:

var array = ['a', 'b', 'c']; var obj = { array[1]: 'good' } 

The above error.

Update: In fact, I am passing the object as part of another array, i.e. A simplified example would be:

 aObj[value] = ['one', {array[1]: 'good'}, 'two', 'three', 'four']; 

Style Setting obj[array[1]] = 'good'; means use

 aObj[value][1][array[1]] = 'good'; 
+6
source share
2 answers

{ array[1]: 'good' } throws an error because when you use Object literal notation in JavaScript, it treats the string before : as an identifier, and the name of a valid identifier cannot contain [ or ] .

So, use the [] notation, which allows you to use any string as the property name, for example this

 var array = ['a', 'b', 'c']; var obj = {}; obj[array[1]] = 'good'; 
+5
source

Maybe it's time to start giving answers to ES6. In ECMAScript6, you can use expressions as keys of objects:

 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 a variable is to use parenthesized notation as described in another answer.

+3
source

Source: https://habr.com/ru/post/982989/


All Articles