[英]jQuery autocomplate parse specific array of data from json object
I have some problem with here jquery here. 我在这里jquery有一些问题。 So I want to make an autocomplete text field using json object from database, here I provide my code
所以我想使用数据库中的json对象创建一个自动完成的文本字段,在这里我提供我的代码
jQuery : 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 我不想像我一样返回值json对象,我只需要数组形式的school_name ,请帮助我解决问题
Use response
callback to push data you want. 使用
response
回调来推送所需的数据。
$('#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);
});
}
});
You can use Array.prototype.map
to transform an array. 您可以使用
Array.prototype.map
转换数组。 map
will run a function over each item in the array and create a new array with the returned values. map
将对数组中的每个项目运行一个函数,并使用返回的值创建一个新数组。
const json = { "status": "success", "result": { "data": [ { "school_id": '1234', "school_name": "First School Name", "status": "Swasta", "address": "xxx", "city": "BANYUWANGI", "province": "JAWA TIMUR", "phone": "1234", "email": "xx@a.co", "picture": null, "is_published": "Y" }, { "school_id": '5678', "school_name": "Second School Name", "status": "Swasta", "address": " ", "city": "", "province": "", "phone": "-", "email": null, "picture": null, "is_published": "Y" } ] } } console.log( json.result.data.map(school => school.school_name) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.