javascript - How to map AJAX JSON to Label & Value? -
i have current function uses ajax. retrieves json list of objects correctly. each object has id & name. i'm unsure how map each object id value , each name label when user chooses option, can process selection.
$(function() { var namearray = []; $("#search").autocomplete({ source : function(request, response) { $.ajax({ url : "controller", type : "get", data : { term : request.term }, datatype : "json", success : function(data) { $.each(data,function(key,val){ namearray.push(val.name); }); response(namearray); } }); } });
at moment read names in array , send through response used in jquery-ui autocomplete. need way send both val.name & val.id.
this can later use 'ui.item.label' , 'ui.item.value' within select:function.
thanks
you need push object array has properties want.
success : function(data) { var namearray = []; $.each(data,function(key,val){ namearray.push({value:val.name, label:val.name, id: val.id}); }); response(namearray); }
you simplify little bit using array.prototype.map()
var namearray = data.map(function(item){ return {value: item.name, label: item.name, id: item.id}; });
Comments
Post a Comment