lorenzo
lorenzo

Reputation: 534

iterating over JSON in javascript to put into select options

I keep having issues iterating over some JSON to put in select options
(btw, ignore the actual values for "label", those are garbage atm).

Here is an example that my php is passing into this:

[{"value":"1","label":"04-22-12"},{"value":"4","label":"04\/04\/12"}]

I am currently trying this loop: *note, dateSelect is defined somewhere else

for (res in JSON.parse(request.responseText)) {
    var date = document.createElement("option");
    date.value = res.value;
    date.text = res.label;
    dateSelect.add(date, null);
}

However, it is adding "undefined" into my options... How do I get it so each value and corresponding label is put in there correctly?

Upvotes: 2

Views: 541

Answers (1)

user1106925
user1106925

Reputation:

You have an Array, so don't for-in.

In your code, res is the property name (the index of the Array in this case) in the form of a string, so the properties you're looking for aren't going to be defined on the string.

Do it like this...

for (var i = 0, parsed = JSON.parse(request.responseText); i < parsed.length; i++) {
    var res = parsed[i];
    var date = document.createElement("option");
    date.value = res.value;
    date.text = res.label;
    dateSelect.add(date, null);
}

Upvotes: 3

Related Questions