rajeev rajeev - 4 months ago 22
JSON Question

select2-4.0.3 displaying values as keys in JSON data

i have this JSON data coming from server. which is valid JSON per JASONlint

issue is when i enter 3 digits (anything bogus) I get the drop down, and it shows "keys" as values!!! I do not know why it is in reverse order??? if i use .each in place of .map it correctly lists values as values (in console log), but then shows nothing in dropdown (some error in select2 js is reported).

JSON: (firebug)

{"4":"2013","3":"2014","1":"2016","6":"winter","7":"birthday","2":"2015","5":"summer","8":"vacation"
}


this is my JS:

$("#selectTags").select2({
tags: true,
multiple: true,
allowClear: true,
//closeOnSelect: false,
tokenSeparators: ',', // [' ',','],
minimumInputLength: 3,
ajax: {
url: "/cgi-bin/json-data.pl",
dataType: 'json',
delay: 100,
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (key,value) {
console.log('key='+key);
return {
id: key,
text: value
}
})
};
}
}
});

Answer

the problem is with map, you have mixed up arguments, the first is value, the second is key. see http://api.jquery.com/jQuery.map/#jQuery-map-object-callback

    processResults: function (data) {
        return {
            results: $.map(data, function (value, key) {
                console.log('key='+key);
                return {
                    id: key,
                    text: value
                }
            })
        };
    }