tags:

views:

139

answers:

2

I have a Json object in which I would like to fill a drop down list with distinct values selected from a field of my Json object

A: 

This should work.

var s = [];
for (var n in obj) {
    if (obj.hasOwnProperty(n)) {
        s.push("<option value='");
        s.push(n);
        s.push("'>");
        s.push(obj[n]);
        s.push("</option>");
    }
}
$("select").append(s.join(""));
ChaosPandion
Any particular reason you're using the "StringBuilder" style rather than straight concatenation?
Matt Ball
@Bears will eat you - To keep things interesting.
ChaosPandion
@bears if he has a long list of items, chaos's way is going to be a LOT faster in older browsers (and in some newer ones) than straight string concatenation
Jason
@Bears, @Jason - Yep, depending on the implementation it should really cut down on the number of copies being made. *(Although for all we know, under the covers the strings could behave more like string builders for some implementations but I doubt that is the case.)*
ChaosPandion
@Chaos - I cant understand why you go halfway to a string builder solution then use + concatenation. Surely you should push each distinct string onto the array if you are concerned about this?
James Westgate
@James - That is because I am not really concerned about it but I will update to meet your standards. :)
ChaosPandion
@Jason - last time I tested (about a year ago), IE was the only browser in which "StringBuilder" is faster.
Matt Ball
Jason
@Jason - my copy arrived today :). Even better, I tested out the StringBuilder style vs concatenation in the same context as I did before, and StringBuilder == _much faster_.
Matt Ball
@bears it's a great book, isn't it? :)
Jason
A: 
var myList = $('#select');
for (var n in obj) {
    myList.append($('<option></option>').val(obj[n]).text(n));
}
Silkster