如何使用jQuery将JSON数据推送到数组中?
问题描述:
我是jQuery的新手,我正在尝试使用getJSON
函数。我想要做的是拉JSON文件的“id”部分,并将其推入jQuery中名为planes
的数组中。从那里,该数组用于自动填充功能来填充可搜索的ID。如何使用jQuery将JSON数据推送到数组中?
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来更新你的$ .each行(这是你的错误代码的其余部分很好)。
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链接Plunker
答
你也可以考虑本地阵图的方法,它可以节省您不必创建一个数组,然后推到的东西它。它只是通过在每个项目上应用映射函数而返回给定原始数组的新数组。
$.getJSON("planes.json",function(data){
console.log(data.map(function(plane){return plane.id;}))
}
但是,如果我正确记得,这是不可用在IE < = 8。
顺便说一句,你使用mtgjson.com的数据集?如果没有,那可以为你的项目节省很多时间...... –