1

I am trying to bind a JSON array, which is the result of an Ajax call, to a <select/> element.

A sample of the JSON structure is seen below:

[{"JD_No":1,"JD_Name":"Network Administrator"}, {"JD_No":2,"JD_Name":"System Administrator"}]

What I need to achieve is to extract the JD_No value and JD_Name value of each element and bind them to a html <select/>

I must also state that the JSON Key is dynamic, so referencing a specific Key Name will not be possible.

Any help please?

Rudolf Lamprecht
  • 1,050
  • 1
  • 14
  • 37

6 Answers6

3

in jQuery you can do this:

you can check if the value is a type number, if not then it is a name.

JSFiddle here

var jsonString = '[{"JD_No":1,"JD_Name":"Network Administrator"}, {"JD_No":2,"JD_Name":"System Administrator"}]';

var json_data = JSON.parse(jsonString);

for(var i = 0; i < json_data.length; i++){

    var option = $("<option>");

    for( var key in json_data[i] ){
        // There should only be two keys, if its a number its ID, else option name
        if( typeof json_data[i][key] === "number" ){
            option.attr("value", json_data[i][key]);
        }else{
            option.html(json_data[i][key]);
        }
    }

    $("select").append(option);

}
AlexCheuk
  • 5,595
  • 6
  • 30
  • 35
2

Try this http://jsfiddle.net/SPMJz/

HTML

<select id="select"></select>

Javascript

window.onload = function(){
    var data = [
        {"JD_No":1,"JD_Name":"Network Administrator"},
        {"JD_No":2,"JD_Name":"System Administrator"}
    ];

    populateSelect(data, 'number', 'string');
}

function populateSelect(data, idType, nameType){
    if(!data || !data[0]){
        return;
    }

    var select  = document.getElementById('select');
    var keys    = Object.keys(data[0]);
    var idKey   = typeof(parseInt(keys[0])) == idType   ? keys[0] : keys[1];
    var nameKey = typeof(parseInt(keys[0])) == nameType ? keys[0] : keys[1];

    for(var i = 0; i < data.length; i++){
        var option = document.createElement('option');
        option.value = data[i][idKey];
        option.label = data[i][nameKey];
        select.appendChild(option);
    }
}
Dart
  • 787
  • 1
  • 7
  • 16
1

If I understand correctly, you want to bind dynamic properties to the select? If you can assume that the list of objects will always be returned with a specific amount of properties in a specific order, you can access the properties based on their INDEX.

The following example gets a key and value from an object:

for (var i in myArray) {
    var obj = myArray[i];
    var index = 0;
    var key, val;
    for (var prop in obj) {
        switch (index++) {
            case 0:
                key = obj[prop];
                break;
            case 1:
                val = obj[prop];
                break;
            default:
                break;
        }
    }
    $("select").append("<option value=\"" + key + "\">" + val + "</option>");
}
FarligOpptreden
  • 5,013
  • 22
  • 23
1

Based on the assumption that your option's value attribute will always be a number.

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 Demo

A jQuery solution:

$.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);
});
c.P.u1
  • 16,664
  • 6
  • 46
  • 41
0

Consider that json is the object that array of objects you have in question. Iterate the array, collect each obj, access the keys as you require. Generate an element and store data- attributes equal to the keys in the array.

$.each(json, function(i, obj){
    $('body').append('<select data-no="'+obj.JD_No+'" data-name="'+obj.JD_Name+'"></select>');
});
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
0

let jsonArray be your json data, then you can bind the data to a select element using the following code

$.each(jsonArray, function (index, item) {
                 $('#ddl').append($('<option></option>').val(item.JD_No).html(item.JD_Name));
             });
iJade
  • 23,144
  • 56
  • 154
  • 243