gpt4 book ai didi

javascript - 迭代 JSON 对象以获取自动完成建议

转载 作者:行者123 更新时间:2023-12-02 19:32:12 25 4
gpt4 key购买 nike

我收到了从源收到的以下对象 -

["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k":1,"q":"lpxvQlflqTsJ-2_PMBLImSpu1PU"}]

我想从对象中获取的值:

road, roadtrip, roadrunner, roadster and so on.

这是代码

    $('#query').autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: , // url for the source
dataType: "json",
data: {
"tags" : request.term
},
success: function( data ) {
related = data[1];
response(data[1][0]);
}
});
}

但是我只从对象的第一个数组中获取值?例如。 公路原配

应该如何迭代来获取它的值?

最佳答案

这是一个数组而不是一个对象,如果你 JSONLint它:

[
"road",
[
[
"road",
53,
"0E"
],
[
"roadtrip",
53,
"1E"
],
[
"roadrunner",
53,
"2E"
],
[
"roadster",
53,
"3E"
],
[
"roadside",
53,
"4E"
],
[
"roadrage",
53,
"5E"
],
[
"roadcycling",
53,
"6E"
],
[
"roadsideamerica",
53,
"7E"
]
],
{
"k": 1,
"q": "lpxvQlflqTsJ-2_PMBLImSpu1PU"
}
]

您可以看到第一个键是字符串“road”,第二个键是一个数组,最后一个键是一个对象。

您要查找的项目是主数组的第二个键中的数组的第一个键。

尝试如下:

$('#query').autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: , // url for the source
dataType: "json",
data: {
"tags" : request.term
},
success: function( data ) {
var terms = [];

for (var i=0; i < data[1].length; i++) {
terms.push(data[1][i][0]);
}

respond(terms);
}
});
}

关于javascript - 迭代 JSON 对象以获取自动完成建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11366778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com