1

I am using jqueryui autocomplete and would like to know if there is a generic way to access the Json object items using $.ajax(). In the example below, the text/value pairs are item.Title and item.AlbumId and it works fine. But I would like to know if there is a way to access it like item[0], item[1]. I tried but it does not work.

    // jqueryui autocomplete configuration
    $(element).autocomplete({
                   minLength: minimumTextLength, 
                   source: function (req, response) {    

                       // call $.ajax()
                       $.ajax({
                           url: filterUrl,
                           type: "POST",
                           dataType: "json",
                           data: { term: textbox.val() },
                           success: function (data) {
                               response($.map(data, function (item) {

                                   return { label: item.Title, value: item.AlbumId }; 
                               }));
                           }
                       });

                   }
               }); //  end of autocomplete()
user2813261
  • 625
  • 1
  • 8
  • 18

1 Answers1

0

You could do this indirectly, using Object.keys. That way you can reference item[keys[index]]:

response($.map(data, function (item) {
    var keys = Object.keys(item);
    return { label: item[keys[0]], value: item[keys[1]] }; 
}));

Note that Object.keys is only supported by modern browsers (IE9+). Although, as always, you can polyfill if needed.

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260