2012-10-10 49 views
0

可能重複:
Find object by id in array of javascript objects訪問數據arrray

所以我有這樣的:

mapArray= 
[{"Title":"crop_rotation","subs":"5,6,7,10"}, 
{"Title":"cover_crops","subs":"2,5,7,8,9,13,14"}, 
{"Title":"binary_wetlands","subs":"1,2,3,4,5,6,7,8,9,10,11"}] 

我試圖訪問基於該潛艇值標題。我想

listofSubs=mapArray["crop_rotation"]("subs"); 

我沒有得到任何東西回來。我在這裏錯過了什麼?我需要將該列表轉換爲字符串,但我認爲它會以字符串的形式出現,因爲我已經解析了該對象?在此先感謝

回答

3

首先,您必須找到具有特定標題的對象。您可以通過遍歷數組過來,比較要做到這一點每個對象的Title對你的價值:

function find(arr, key, value) { 
    for(var i = 0, l = arr.length; i < l; i++) { 
     if(arr[i][key] === value)) { 
      return arr[i]; 
     } 
    } 
    // return {}; // if you would want it null-safe 
} 

然後你就可以訪問相應的subs屬性:

var obj = find(mapArray, 'Title', 'crop_rotation'); 
if(obj) { 
    var listofSubs = obj.subs; 
} 

能夠解釋爲什麼你代碼不起作用:

mapArray["crop_rotation"]("subs"); 
//  |-  1  -|- 2 -| 
  • |1|嘗試訪問mapArray中對象的屬性crop_rotation。數組沒有這樣的屬性,在你的情況下沒有任何對象。 crop_rotation是其中一個屬性的
  • |2|是一個函數調用。它試圖調用mapArray["crop_rotation"]引用的函數並將第一個參數作爲"subs"。它會拋出一個錯誤,如果mapArray["crop_rotation"]不是一個函數(就像你的情況)。

進一步的信息:

+0

優秀的答案和一段代碼我會放在阿森納。感謝您的幫助Felix。 – jeynon

+0

$。每個(forMapArray,函數(指數,值){ \t如果(forMapArray [指數] [ 「標題」] == 「crop_rotation」){ \t警報( 「YES」); \t doCropRotation(); } }); – jeynon

+0

@jeynon:是的,爲了處理滿足特定條件的每個對象,這是有道理的。請注意,您也可以這樣做:'if(value [「Title」] ==「crop_rotation」){...}' –

0

alert(mapArray[0].Title) =「crop_ro 「

+0

只需返回1。 – jeynon

0

你有什麼是對象數組。數組被數字化索引。因此,爲了得到你正在尋找的價值:

mapArray; // returns array of objects 
mapArray[0]; // returns first object in the array 

// returns the value of the `"subs"` key in the first object in the array 
mapArray[0]['subs']; 

注意這個書名不會找到它,你需要的是多一點的邏輯。請參閱Felix Kling的答案,

0

您可以'通過它的元素的字段來訪問列表(數組)。它的目的是命名爲list(數組),它不是以任何東西而是以位置索引。所以你可以像這樣訪問listArray [0]。如果想通過標題來訪問它如果你的輸入是固定的,你不能改變它,你必須進行預處理,以適合您的需求,您應該有structur這樣

{ "crop_rotation": ..., 
    "cover_crops" :...., 
    .... 
} 

。所以你必須遍歷數組,並將字典從它改爲"Title"值到新字典的鍵中。