我有json格式的数据,我尝试用ajax向她展示并成功。但是如何使用ajax在json中找到一个id呢?我的剧本是否正确?例如我想查找 id 2。
我的json
{ "device": [
{
"id": 1,
"name": "Android"
},
{
"id": 2,
"name": "Apel"
},
{
"id": 3,
"name": "Windows"
}
] }
我的ajax
$(document).ready(function() {
var id_pm = 2 ;
var dataString = "id="+id_pm;
$.ajax({
type: "GET",
url: "data.json",
data: dataString,
cache: false,
timeout: 3000,
error: function(){
alert('Error');
},
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id=element.id;
var name=element.name;
});
}
});
});
请您参考如下方法:
Id 应该是唯一的。如果您的 JSON 不包含顺序 id,那么您将必须按顺序扫描所有对象,如下所示:
//put this inside your success callback.
var mysearchId = 2;
//res is now array of all your devices.
var res = (JSON.parse(result)).device;
for(var i = 0;i < res.length;i ++) {
if(res[i].id == mysearchId) {
console.log(res[i]);
return;
}
}
console.log('not found!');
这会在 O(N) 时间内找到所需的项目。
如果您的 id 是连续的,您可以在 O(1) 时间内找到特定元素。要实现此目的,必须对设备数组进行排序。 例如,如果您想查找 id 为 10 的元素,您可以通过 res[(10-1)]; 访问它//==>res[9]; 假设第一个项目的 id=1。






