2016-06-23 63 views
1

undefied我從Java JSON看起來像這樣:JSON的內容(鍵值對)檢索JSON元素給出的jQuery

[{ 
    "col_name_1": "Name", 
    "col_value_1": "Deepu", 
    "col_name_2": "Age", 
    "col_value_2": "22", 
    "col_name_3": "gender", 
    "col_value_3": "Male" 
}] 

一些次數可能會增加或減少。所以我決定在jQuery中使用for loop來檢索數據。我的代碼是:

var tabdata = $.parseJSON(data); 
var ele_count = Object.keys(tabdata[0]).length; 
ele_count = parseInt(ele_count)/2; //total key-value pair 

for (var j = 1; j <= parseInt(ele_count); j++) { 
    var cn = "col_name_" + j; 
    var cv = "col_value_" + j; 
    alert(tabdata[0].cn); 
    alert(tabdata[0].cv); 
} 

這兩個警報都給出undefined。但使用 tabdata[0].col_name_1tabdata[0].col_value_1等給出了所需的結果。問題出在for循環內。有人能幫我嗎?

+0

我見過 – madalinivascu

+0

最醜陋的JSON @ madalinivascu,其創建使用循環 – next2u

回答

0

嘗試了jQuery each功能

var obj = [{"col_name_1":"Name","col_value_1":"Deepu","col_name_2":"Age","col_value_2":"22","col_name_3":"gender","col_value_3":"Male"}] ; 

$.each(obj[0],function(i,v){ 
console.log(v); 
}); 

demo

1

通過變量訪問對象的屬性時,您需要使用括號標記。試試這個:

for (var j = 1; j <= parseInt(ele_count); j++) { 
    var cn = "col_name_" + j; 
    var cv = "col_value_" + j; 
    console.log(tabdata[0][cn]); 
    console.log(tabdata[0][cv]); 
} 
0

使用您的內部下面的for循環

tabdata[0][cn]