2017-08-02 58 views
0

我需要在一個Ajax調用充分利用對象的值在JavaScript

代碼段

$.each(responseJson.slice(0,7), function (index) { 
var resp_JSON=responseJson[index]; 
console.log(resp_JSON); 

在控制檯從響應對象獲取值幫助resp_JSONObject {17130003: "A message string from the cache"}

現在響應的Json沒有名稱標籤,所以我可以做resp_JSON.id或&獲取值。它只是有價值。

我試圖

resp_JSON[0]; //錯誤

resp_JSON.Object[0]; //錯誤

我需要在兩個單獨的JavaScript變量獲取17130003 & A message string from the cache

+3

其實你需要訪問'resp_JSON ['17130003']',如果這些鍵是動態的,你可以使用'Object.values(resp_JSON)'和'Object.keys(resp_JSON)' –

+1

@HassanImam感謝兄弟的工作。 – underdog

回答

1

爲了得到的對象。你可以這樣做:

var keys = Object.keys(resp_JSON); // [17130003] 
var values = Object.values(resp_JSON); // ["A message string from the cache"] 

請注意,兩者都是數組,你可以簡單地遍歷數組來處理每個值/鍵。

此外,正如@Hassan指出的那樣,如果這就是你想達到的目標,你可以通過resp_JSON['some_key']得到具體的價值。