2017-02-22 127 views
0

我有json格式的數據,我試圖用ajax顯示她併成功。但如何在json中使用ajax找到一個id?以及腳本是否正確?例如,我想查找ID 2用ajax json獲取基於id的數據的值

我的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; 
      }); 
     } 
    }); 
}); 
+1

*「以及腳本是否正確?」 - 嗯,當你運行它時發生了什麼? – nnnnnn

+0

是的我期望如何查找'id' = 2的data.json,而不使用查詢url –

+1

可能重複的[從值或屬性的對象數組中獲取JavaScript對象](http://stackoverflow.com/questions/ 13964155/get-javascript-object-by-array-of-objects-by-value-or-property) – Rajesh

回答

1

ID是意味着是unique.If數據的JSON不包含順序標識符,那麼您將不得不按順序掃描所有這樣的對象:

//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)時間內找到特定元素。要實現這一點,必須對devices數組進行排序。 例如,如果要查找ID爲10的元素,則可以通過res[(10-1)]; //==>res[9];訪問它,前提條件是第一項具有id = 1。

0

您可以使用過濾功能來過濾基於ID

var data = { 
      "device": [ 
     { 
      "id": 1, 
      "name": "Android" 
     }, 
     { 
      "id": 2, 
      "name": "Apel" 
     }, 
     { 
      "id": 3, 
      "name": "Windows" 
     } 
      ] 
     }; 

     var res = data.device.filter(function (obj) { 
      return obj.id == 2; 
     }); 

if(res.length){ 
    console.log(res[0].id); 
    console.log(res[0].name); 
} 
+1

'Array.find' would like more – Rajesh

+0

同樣你不應該關閉這個問題的重複,因爲有許多帖子*基於關鍵*獲取對象? – Rajesh

+0

@Mairaj,謝謝你的回答,但我的數據在url ex.'http:// project/data.json文件中 –