2017-08-02 28 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']得到具体的价值。