如何在数组中获取json响应

时间:2012-04-06 12:48:11

标签: javascript jquery json arrays

我在jquery中发出一个ajax请求,然后获得响应,但不是作为数组。

{"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}}
{"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}

我想合并上面的两个响应并创建一个类似这样的数组:

{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}

请建议如何操作。我想把它放在数组中并在本地存储它可能在配置变量get:[]然后访问有点像config.get[data["seriesId"]]

3 个答案:

答案 0 :(得分:0)

你可以做到

var obj1 = {"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}};

var obj2 = {"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}};

var arr = [];

arr.push(ob1.SeriesSocialStats);
arr.push(ob2.SeriesSocialStats);

答案 1 :(得分:0)

最好的方法是将服务器响应转换为数组结构,如Joseph所提到的,而不是从对象到数组进行双重处理。

答案 2 :(得分:0)

您需要将响应转换为数组对象:

var response = [
    {"ErrorCode":0,...},
    {"ErrorCode":0,...},
    {"ErrorCode":0,...},
]

实际上:

jsonResponse = [
    {"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}},
    {"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}
]

然后循环:

var newArray = []
for(var i=0;i<jsonResponse.length;i++){             //loop through items
    var stats = jsonResponse[i].SeriesSocialStats;
    for(key in stats){                              //loop through "SeriesSocialStats" numbers
        newArray.push(stats[key]);
    }
}

所以它会像:

newArray = [
    {"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},
    {"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}
]