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?

6
  • Place it in the data-* property, then recall it. You can use jQuery's .data() for this. Commented Sep 13, 2013 at 6:27
  • are you saying JD_No will not always be the key? Commented Sep 13, 2013 at 6:29
  • That is correct Alex. But the structure will always be 2 KeyValue pairs within a single object Commented Sep 13, 2013 at 6:30
  • when you say bind, you mean add options with those values to the select? Commented Sep 13, 2013 at 6:32
  • Indeed Koala, each object will be bound as an option in a select element. Commented Sep 13, 2013 at 6:33

6 Answers 6

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);

}
Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

Comments

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>");
}

2 Comments

each array item is an object, you cant access it like an array.
you're right - you have to access the associative "property array" by the key. I amended my answer.
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);
});

Comments

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>');
});

1 Comment

Thanks, but as stated in my original post, the Key names will be dynamic and not known at the time.
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));
             });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.