如何使用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"} 
] 

Plunker

任何帮助深表感谢。

+0

顺便说一句,你使用mtgjson.com的数据集?如果没有,那可以为你的项目节省很多时间...... –

你几乎已经拥有了它,虽然你正在循环着data.id这不是你想要做的。您应该循环访问data,然后按val.id

如果你想遍历data.id,那么你JSON必须像这样被结构化:

{ 
    "id": [ 
     "things", 
     "to", 
     "loop", 
     "through" 
    ] 
} 

..但它不是,所以只是通过数据循环。

+1

就是这样!谢谢你的帮助。此外,它看起来像我可以有不同的结构我的JSON,使这更容易一些。 – Thassa

+1

很高兴听到:3 – bitten

请检查以下解决方案。我有硬编码的平面数据,而不是从文件中获取,但解决方案是相同的。你只需要通过遍历数据而不是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。