How to assign key to object literal when they keyname is represented by a variable?

91 Views Asked by At

Perhaps someone can help me solve this.

I'm pulling input elements' name and value out of a list like this simplified version:

<ul id="options_set_1">
    <li><input name="width" value="10" /></li>
    <li><input name="height" value="20" /></li>
    <li><input name="depth" value="5" /></li>
</ul>

The id of the ul and the names and values of the inputs are then assigned to variables so the final representation is:

var optionsSet1 = "options_set_1"
var name1 = "width"
var value1 = "10"
var name2 = "height"
var value2 = "20"
var name3 = "depth"
var value4 = "5"

I then have an empty object which I need to populate as follows:

signState = {};

signState[optionSet1] = {name1 : value1};

The object is populated, but the problem is that 'name1' does not reflect the variable value which is "width". How do I get the object to not take the variable name and literally assign it as the key name?

1

There are 1 best solutions below

1
On BEST ANSWER

In the same way you already used it with optionSet1 – using the bracket notation:

signState = {};

signState[optionSet1] = {};

signState[optionSet1][name1] = value1;