Reputation: 4559
I have an object
var myObject = { 3: 'Three', 6: 'Six'};
I want to populate those values in a dropdown like so:
var statusDropdown = document.createElement('select');
for (var item in myObject ) {
var option = document.createElement("option");
option.text = item.value; //this is undfined item = "Three", or "Six"
option.value = item.key; //this is undfined item = "Three", or "Six"
statusDropdown.options.add(option);
}
for in seems the way to go but I am trying to do key and value not just value. This would allow me to set the key to 3 for the first dropdown option, and 6 for second
Upvotes: 0
Views: 160
Reputation: 2257
the code in for loop should be like this.
option.text = myObject[item];
option.value = item;
Upvotes: 0
Reputation: 71939
In for (var item in myObject )
, item
is the key, and the value will be at myObject[item]
. So:
for (var item in myObject ) {
var option = document.createElement("option");
option.text = myObject[item];
option.value = item;
statusDropdown.options.add(option);
}
Upvotes: 1
Reputation: 53351
It's kind of confusing, but item
actually holds the key to the current property, not the actual property itself. Using myObject[item]
will fix the issue.
Upvotes: 1