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
2010-08-26 19:19:19
Any particular reason you're using the "StringBuilder" style rather than straight concatenation?
Matt Ball
2010-08-26 19:20:31
@Bears will eat you - To keep things interesting.
ChaosPandion
2010-08-26 19:21:31
@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
2010-08-26 19:24:54
@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
2010-08-26 19:40:44
@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
2010-08-26 19:47:03
@James - That is because I am not really concerned about it but I will update to meet your standards. :)
ChaosPandion
2010-08-26 19:48:52
@Jason - last time I tested (about a year ago), IE was the only browser in which "StringBuilder" is faster.
Matt Ball
2010-08-26 19:58:14
Jason
2010-08-27 17:27:50
@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
2010-09-03 21:54:42
@bears it's a great book, isn't it? :)
Jason
2010-09-03 23:23:36
A:
var myList = $('#select');
for (var n in obj) {
myList.append($('<option></option>').val(obj[n]).text(n));
}
Silkster
2010-08-26 20:36:09