Reputation: 496
I have string of data coming to the page via ajax. in the following format
[{"servername":"svrA"},{"servername":"svrB"},{"servername":"svrC"},{"location":"locA"},{"location":"locB"},{"location":"locC"}]
I'd like to populate two select boxes with the data.
I've tried different variations of the following pseudo code:
for each item in the json string
if obj == servername
add to selectbox Server
if obj == location
add to selectbox Location
Any ideas would be greatly appreciated. Thanks.
Upvotes: 0
Views: 458
Reputation: 43718
There are several ways to do this and depending on how your code might evolve in the future, some solutions might be slightly better than others or more flexible, but since I do not have such knowledge, here's an example on how you could do it in vanilla JS.
var data = [
{"servername":"svrA"},
{"servername":"svrB"},
{"servername":"svrC"},
{"location":"locA"},
{"location":"locB"},
{"location":"locC"}
],
selects = {
servername: document.getElementById('servername'),
location: document.getElementById('location')
},
i = 0,
len = data.length,
item, prop, val;
for (; i < len; i++) {
prop = 'servername' in (item = data[i])? 'servername' : 'location';
val = item[prop];
selects[prop].add(new Option(val, val), null);
}
If you plan having the same kind of data structure for multiple select boxes, instead of hardcoding the selects
object that references the select
elements, you could also have pulled the select id
dynamically using for in
and also resolve the select
reference using a generic approach.
Upvotes: 1
Reputation: 28125
var stuff = [{"servername":"svrA"},{"servername":"svrB"},{"servername":"svrC"},{"location":"locA"},{"location":"locB"},{"location":"locC"}];
var elems = {
"servername": jQuery('#select-server'),
"location": jQuery('#select-location')
};
stuff.forEach(function(item){
for(var selectName in elems){
if(typeof item[selectName] != 'undefined'){
var val = item[selectName];
elems[selectName].append(jQuery('<option/>').val(val).html(val));
}
}
});
Not that forEach
is not available on older browsers. The code above is just a sample for you to work with.
Upvotes: 1