2016-03-28 118 views
-4

我有以下json數組結構..我怎樣才能得到每個records json對象的關鍵和值?如何循環json數組以獲取鍵和值在JavaScript中?

{ 
    "records": [{ 
     "cfsub_2": "1", 
     "cf_7": "1/3/2016", 
     "cf_1": "Clinic San", 
     "cf_2": "Fever", 
     "cf_3": "56.60", 
     "cfe_8": "dsf4334" 
    }, { 
     "cfsub_2": "2", 
     "cf_7": "3/3/2016", 
     "cf_1": "Clinic Raju", 
     "cf_2": "braces", 
     "cf_3": "183.50", 
     "cfe_8": "fresr4" 
    }] 
} 

我的預期成果是得到鍵和值...下面的例子:

<b>key</b> : cf_1, <b>value</b> : Clinic San 

我試圖環在records,但因爲我不知道key,所以我無法獲得的價值..

for (var z in records) 
{ 
    var value = records[z].cf_1; 
    alert(value); 
} 

//i don't know the key here.. i want to get the key and value 

完整的JSON結構如下:

{ 
"forms": [{ 
    "id": 1, 
    "records": [{ 
     "cfsub_2": "1", 
     "cf_7": "1/3/2016", 
     "cf_1": "Clinic San", 
     "cf_2": "Fever", 
     "cf_3": "56.60", 
     "cfe_8": "dsf4334" 
    }, { 
     "cfsub_2": "2", 
     "cf_7": "3/3/2016", 
     "cf_1": "Clinic Raju", 
     "cf_2": "braces", 
     "cf_3": "183.50", 
     "cfe_8": "fresr4" 
    }] 
}, { 
    "id": 7, 
    "records": [{ 
     "cf_31": "27/3/2016", 
     "cf_32": "Singapore", 
     "cf_33": "dfd555", 
     "cfe_34": "" 
    }] 
}, { 
    "id": 11, 
    "records": [{ 
     "cfsub_10": "9", 
     "cf_9": "25/3/2016", 
     "cf_10": "256.50", 
     "cfe_11": "dfg44" 
    }] 
}] 
} 
+0

請澄清一下你想要什麼,你現在擁有什麼,期望的輸出是什麼,以及你已經試圖解決這個問題。 –

回答

-1
var getKeys = function (arr) { 
    var key, keys = []; 
    for (i = 0; i < arr.length; i++) { 
     for (key in arr[i]) { 
      if (arr[i].hasOwnProperty(key)) { 
       keys.push(key); 
      } 
     } 
    } 
    return keys; 
}; 
0

希望這個對你有幫助。

$.each(value.forms, function(index,array){ 
    $.each(array.records, function(ind,items){ 
     $.each(items, function(indo,itemso){ 
      alert("Key -> "+indo + " : values -> " + itemso); 
     }); 
    }); 
}); 
+0

這段代碼解決了你的問題嗎? –

相關問題