2016-11-27 144 views
-3

我是JavaScript和JSON的新手。我有這樣的JSON:從JSON中提取數據返回undefined

data = [[{"checked":false,"no":"1"},{"checked":true,"no":"2"}]] 

但我很難通過循環來獲取「檢查」值。

我用於循環,然後我嘗試console.log data.checked但它總是返回undefined。如何做到這一點?

+0

這不是JSON! – Oriol

+0

因爲你檢查了數組,請刪除一對括號 – stasovlas

回答

1

使用索引獲取第一個數組元素並使用Array#forEach方法進行迭代。

var data = [ 
 
    [{ 
 
    "checked": false, 
 
    "no": "1" 
 
    }, { 
 
    "checked": true, 
 
    "no": "2" 
 
    }] 
 
]; 
 

 
data[0].forEach(function(v) { 
 
    console.log(v.checked); 
 
})

+1

謝謝!有用。 – sse

0

你有一個嵌套的數組,所以訪問成員對象,你需要在data[0]訪問它們的checked財產。

let innerData = data[0]; 
for(let i = 0; i < innerData.length; i++) { 
    console.log(innerData[i].checked); 
} 
0

在你的JSON,你有一個頂層數組,那裏面,你有陣列(S)的另一個層面,而數組中你的對象。所以你應該做的是這樣的。

for (var i = 0; i < data.length; ++i) { 
    for (var j = 0; j < data[i].length; ++j) { 
    console.log(data[i][j], data[i][j].checked); 
    } 
} 
0

你可以擺脫雙重嵌套數組與

array = array[0]; 

然後循環爲你總是循環。

0
// This is array in array with object 
var data = [[{"checked":false,"no":"1"},{"checked":true,"no":"2"}]] 


for(var i = 0 ; i < data.length ; i++){ // Test the length of first array and go inside 
    for(var z = 0 ; z < data[i].length ; z++){ // When you are inside the array go to another one array and inside go and search 'chacked' 
     console.log(data[i][z]['checked']); // show value of the checked 
    } 
}