2017-09-05 31 views
3

我無法訪問DATA數組內的數字,這將是COLUMNS中提到的ID。從JSON數組中挑選第一個元素,jquery沒有標識符

我的JSON如下:

{ 
    "COLUMNS": [ 
    "ID", 
    "DESCRIPTION", 
    "DATE" 
    ], 
    "DATA": [ 
    [ 
     53, 
     "Try to do something test123", 
     "September, 05 2017 00:00:00 +0100" 
    ] 
    ] 
} 

我現在的嘗試是這樣,但是,我得到了整個3元

var jsonLength= JSON.DATA.length; 

    for (dataIndex = 0; dataIndex < jsonLength; dataIndex++) { 

     var dataLength= JSON.DATA[dataIndex].length; 

     for (noteIndex = 0; noteIndex < dataLength; noteIndex++) { 

      alert(JSON.DATA[dataIndex]); 

     } 
    } 
+0

你試過像這樣'DATA [0] [0]' – guradio

+0

現在我要感謝Rory McCrossan的回答。 –

回答

4

你的代碼幾乎是正確的,你只是缺少2D DATA陣列上的第二個索引存取器。您可以使用noteIndex遞增變量從你的循環:

var JSON = { 
 
    "COLUMNS": [ "ID", "DESCRIPTION", "DATE" ], 
 
    "DATA": [ 
 
    [ 53, "Try to do something test123", "September, 05 2017 00:00:00 +0100" ] 
 
    ] 
 
} 
 
var jsonLength = JSON.DATA.length; 
 

 
for (dataIndex = 0; dataIndex < jsonLength; dataIndex++) { 
 
    var dataLength = JSON.DATA[dataIndex].length; 
 
    for (noteIndex = 0; noteIndex < dataLength; noteIndex++) { 
 
    console.log(JSON.DATA[dataIndex][noteIndex]); // note the additional [] here 
 
    } 
 
}

2
var jsonLength= JSON.DATA.length; 

    for (var i = 0; i < jsonLength; i++) { 

     var note = JSON.DATA[i] 
     var id = note[0] // access id value 

    } 

另外,如果你是服務器的所有者,爲什麼不回到更合適和優選JSON結構也是這樣嗎? :

[ 
    {"id": 1, "description": "..."}, 
    {"id": 1, "description": "..."} 
] 
相關問題