我对jQuery并不熟悉,我正在尝试getJSON函数。我想要做的是提取JSON文件的"id“部分,并将其推到一个名为planes in jQuery的数组中。在那里,数组被用于一个自动完成函数来填充可搜索的ID。
var planes = [];
$.getJSON('planes.json', function(data) {
console.log('Filling array...');
//This is where I think the issue is occurring.
//Is using the name of the section you want to use the correct syntax here?
$.each(data.id, function (index, val) {
planes.push(val.id);
console.log('Pushed ' + index);
});
});
// After getJSON, array should look something like this:
// var planes = [
// 'Alara',
// 'Fiora',
// 'Innistrad',
// 'Kamigawa',
// 'Lorwyn',
// 'Mirrodin',
// 'Ravnica',
// 'Shandalar',
// 'Zendikar'
// ];JSON文件排列如下:
[
{"id": "Ravnica"},
{"id": "Lorwyn"},
{"id": "Innistrad"},
{"id": "Zendikar"},
{"id": "Kamigawa"},
{"id": "Mirrodin"},
{"id": "Shandalar"},
{"id": "Alara"},
{"id": "Fiora"}
]任何帮助都是非常感谢的。
发布于 2016-06-08 16:34:40
您几乎拥有它,尽管您正在循环通过data.id,这不是您想要做的。您应该循环遍历data,并推动val.id。
如果您想遍历data.id,那么您的json必须按照如下的结构:
{
"id": [
"things",
"to",
"loop",
"through"
]
}..but它不是,所以只是循环数据。
发布于 2016-06-08 16:34:54
请检查以下解决方案。我有硬编码的平面数据,而不是从文件中获取,但解决方案是一样的。您只需要通过迭代数据来更新您的$.each行,而不是data.id (这是您的bug,代码的其余部分很好)。
var data = [{
"id": "Ravnica"
}, {
"id": "Lorwyn"
}, {
"id": "Innistrad"
}, {
"id": "Zendikar"
}, {
"id": "Kamigawa"
}, {
"id": "Mirrodin"
}, {
"id": "Shandalar"
}, {
"id": "Alara"
}, {
"id": "Fiora"
}];
var planes = [];
//surround this each with your $.getJSON. I have just hardcoded json data instead of getting it from file
$.each(data, function(index, val) {
planes.push(val.id);
});
console.log(planes);<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您的更新柱塞链接柱塞
发布于 2016-06-08 16:43:40
您还可以查看本机数组映射方法,它可以省去创建数组并将其推送到它上。它只是通过对每个项应用映射函数来返回给定原始数组的一个新数组。
$.getJSON("planes.json",function(data){
console.log(data.map(function(plane){return plane.id;}))
}但是,如果我正确地回忆起来,这在IE<=8中是不可用的。
https://stackoverflow.com/questions/37708076
复制相似问题