2014-09-23 17 views
0

的訪問數組中一個特定的值我有這個數組對象:JavaScript的 - 如何對象

var buArray = [{'31': {'1':'VN', '2':'AC'}}, 
        {'33': {'1':'VN', '2':'AC'}}, 
        {'51': {'1':'VN', '2':'AC', '3':'SR', '5':'WIN'}}, 
        {'52': {'1':'VN', '2':'AC', '3':'SR', '4':'JU'}}, 
        {'53': {'1':'VN', '2':'AC', '3':'SR', '5':'WIN'}}, 
        {'54': {'1':'VN', '2':'AC', '3':'SR', '5':'WIN'}}, 
        {'55': {'1':'VN', '2':'AC', '3':'SR', '6':'PP'}}] 

如何訪問例如該特定對象(ID 31),例如:「 {'31':{'1':'VN','2':'AC'}}「?

最好的問候,

回答

1

您可以使用.filter找到數組中的元素相匹配:

function findEntry(a, key) { 
    return a.filter(function(e) { 
     var k = Object.keys(e); 
     return k.length === 1 && k[0] === key; 
    }); 
} 

結果將仍然是一個數組,但它會僅包含匹配的斷言元素。

如果有可能的是,內部對象可能包含多個鍵,然後用替換return行:

return k.indexOf('31') >= 0; 

NB:Object.keys.filter.indexOf是ES5功能。 Shims適用於較舊的瀏覽器。

0

在標準的javascript中,你必須遍歷每個項目並檢查密鑰。

function find_object_with_key(arr, key) { 
    for(var i = 0;i < arr.length;i++) { // For each index in the array 
     var item = arr[i];    // Retrieve the item 
     for(k in item) {     // For each key in the object 
      if(!item.hasOwnProperty(k)) { // Check if the item is a proper member of the object 
       continue; 
      } 
      if(k == key) {    // Check if the key matches what we are searching for 
       return item;    // Return the item 
      } 
     } 
    } 
    return false;       // In case of failure return false 
} 
+1

不要使用'對...對數組in'! – Alnitak 2014-09-23 11:18:55

0

如果您正在使用underscore.js,您可以使用_.where(list, properties)功能,它,而不是重新發明的機制。你可以在這裏閱讀:http://underscorejs.org/#where

0

這是一個非常混亂的數據結構。此刻,沒有任何對象具有id屬性,因此您無法對其進行查找 - 寫入的方式是您的對象具有屬性 31,33,51等。您必須編寫一個自定義功能來搜索任何對象。

如果可以,我建議再加工的每個對象在陣列中是這樣

{ 
    id: 31, 
    data: { 
     '1':'VN', 
     '2':'AC' 
    } 
} 

但如果不是,與作爲寫入的數據,如下所示(使用簡單的迭代函數,還有更有效的方法)

function findObj(objID, array){ 
    var i, j, len1, len2; 
    for(i = 0, len1 = array.length; i < len1; i++){ 
     var keys = Object.keys(array[i]); 
     for(j = 0, len2 = keys.length; j < len2; j++){ 
      if(keys[j] === objID) { 
       return array[i]; 
      } 
     } 
    } 
    // object hasn't been found 
    return null; 
} 

,因而稱之爲

findObj("31", buArray);