0

我在 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"]].

4

3 回答 3

0

最好的方法是将您的服务器响应转换为数组结构,就像约瑟夫提到的那样,而不是从对象到数组进行双重处理。

于 2012-04-06T13:05:03.467 回答
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);
于 2012-04-06T12:51:27.280 回答
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"}
]
于 2012-04-06T20:45:12.120 回答