[英]How can I use jQuery to push JSON data into an array?
我是jQuery的新手,正在嘗試getJSON
函數。 我想要做的是提取JSON文件的“ id”部分,並將其推入jQuery中稱為planes
的數組中。 從那里開始,該數組用於自動完成功能中以填充可搜索的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"}
]
任何幫助深表感謝。
盡管您正在遍歷data.id
,但您幾乎已經擁有了,這不是您想要做的。 您應該只遍歷data
,然后推入val.id
如果您想遍歷data.id
,那么您的json必須像這樣構造:
{
"id": [
"things",
"to",
"loop",
"through"
]
}
..但事實並非如此,因此只需遍歷數據即可。
請檢查以下解決方案。 我有硬編碼的飛機數據,而不是從文件中獲取,但是解決方案是相同的。 您只需要通過遍歷數據而不是data.id來更新$ .each行(這是您的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>
您的更新插件鏈接Plunker
您還可以查看本機數組映射方法,該方法省去了創建數組然后將內容壓入數組的麻煩。 通過在每個項目上應用映射功能,它只返回給定原始數組的新數組。
$.getJSON("planes.json",function(data){
console.log(data.map(function(plane){return plane.id;}))
}
但是,如果我沒記錯的話,這在IE <= 8中不可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.