0

What I am trying to do is take two properties of a single Javascript object, and creat a new array with the first property as a key for the second one.

var optionArray = {}

for (var i = 0; i < this.collection.models.length; i++) {

  var f = $('.optionChange:eq('+i+')')[0].value;

  if (f === "yes") { 
    this.collection.models[i].set({"optionValue":"yes"});
  }
  else{
    this.collection.models[i].set({"optionValue":"no"});
  }

  var option1 = this.collection.models[i].get("optionName");                  
  var option2 = this.collection.models[i].get("optionValue");
  var result = option1 + ":" + option2;

  optionArray[i] = {
    option1 : option2
  }

};
console.log(optionArray); 

This however only outputs to {option1:"option2 property value"}. The key will not change, it only displays as the word option1. Is there any way to accomplish this?

elclanrs
  • 89,567
  • 21
  • 132
  • 165
Alex Hill
  • 713
  • 1
  • 5
  • 13

2 Answers2

1

This is wrong, since you can't use a variable as the property name when you use {} notation:

optionArray[i] = {
    option1 : option2
}

Try this instead:

optionArray[i] = {} // Make a new empty object
optionArray[i][option1] = option2;
tb11
  • 2,996
  • 20
  • 28
0

You have to write it like this:

optionArray[i] = {}
optionArray[i][option1] = option2;
basilikum
  • 10,014
  • 4
  • 41
  • 55