Mulki Febrianto Mulki Febrianto - 1 month ago 5
Javascript Question

jQuery autocomplate parse specific array of data from json object

I have some problem with here jquery here. So I want to make an autocomplete text field using json object from database, here I provide my code

jQuery :

$('#school_name').autocomplete({
minLength: 3,
autoFocus: true,
source: function(request, response) {
$.getJSON('https://host/path', { q: $('#school_name').val() },
response);
}


Return Json

{
"status": "success",
"result": {
"data": [
{
"school_id": xxx,
"school_name": "xxx",
"status": "Swasta",
"address": "xxx",
"city": "BANYUWANGI",
"province": "JAWA TIMUR",
"phone": "1234",
"email": "xx@a.co",
"picture": null,
"is_published": "Y"
},
{
"school_id": xxx,
"school_name": "xxx",
"status": "Swasta",
"address": " ",
"city": "",
"province": "",
"phone": "-",
"email": null,
"picture": null,
"is_published": "Y"
}
]
}
}


I dont want return value json object like i've got, I only need school_name in array form, please help me to solve my problem

Answer

Use response callback to push data you want.

$('#school_name').autocomplete({
  minLength: 3,
  autoFocus: true,
  source: function(request, response) {

    $.get('https://host/path').always(function(res) {

      var json = JSON.parse(res), result_arr = [];
      $.each(json.result.data, function(k,v) {
          result_arr.push(v.school_name);
      });
      response(result_arr);

    });

  }
});
Comments