0

How to map a complex nested json to jquery autocomplete format? I tried to map my custom json to the required jquery autocomplete format label, value, ... but my list is 'undefined'. This is my setup:

JSON:

{"data":[{"DT_RowId":"row_A6J851","accounts":{"code":"A6J851","name":"Peter Jackson"}},{"DT_RowId":"row_1D01Q14","accounts":{"code":"1D01Q14","name":"Earl Bundy"}}]}

Javascript:

$('#input-search').autocomplete({
source: function ( request, response ) {
  $.ajax({
    type: 'GET',
    url: '/source.php', 
    dataType: "json",
    success: function( data ) {
        response( $.map( data.data.accounts, function( value, key ) {
            return {
              label: value.name,
              value: value.name,
              id: value.code
            }
        }));
      }
    });
},  
create: function() {            
    $(this).data('ui-autocomplete')._renderItem  = function (ul, item) {
        return $( "<li></li>" )
            .append( "<a>" + item.label + "</a>" )
            .appendTo( ul );
    };         
}       
});

1 Answer 1

2

It looks like from your data example that you are not iterating over the nested accounts array, but rather the data array. Try something like this:

$('#input-search').autocomplete({
  source: function ( request, response ) {
    $.ajax({
      type: 'GET',
      url: '/source.php', 
     dataType: "json",
     success: function( data ) {
       var results = [];
       $.each(data.data, function(d){
         var mapped = $.map(d.accounts, function( value, key ) {
          return {
            label: value.name,
            value: value.name,
            id: value.code
           };
          })
         results = results.concat(mapped);       
         });
         response(results);
        }
      });
 },  
 create: function() {            
    $(this).data('ui-autocomplete')._renderItem  = function (ul, item)     {
         return $( "<li>" )
            .append( "<span>" + item.label + "</span>" )
            .appendTo( ul );
  };         
 }       
});
Sign up to request clarification or add additional context in comments.

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.