基于您的期权的价值属性始终是数字的假设。
var json = [{"JD_No":1,"JD_Name":"Network Administrator"}, {"JD_No":2,"JD_Name":"System Administrator"}];
var options = [], key, value;
json.forEach(function(obj) {
Object.keys(obj).forEach(function(k) {
if(typeof obj[k] === "number") {
key = obj[k];
}
else {
value = obj[k];
}
});
options.push({'key': key, 'value': value}); //or append it directly to select
});
options.forEach(function(option) {
var option = $('<option>').attr('value', this.key).html(this.value);
$('#slt').append(option);
});
jsFiddle 演示
一个jQuery解决方案:
$.each(json, function() {
$.each(this, function(k, v) {
if(typeof v === 'number') {
key = v;
}
else {
value = v;
}
});
options.push({'key': key, 'value': value}); ////or append it directly to select
});
$.each(options, function() {
var option = $('<option>').attr('value', this.key).html(this.value);
$('#slt').append(option);
});