JSON:
var res =
{
"response": {
"data": {
"profilesearchsnippet": [
[
{
"profileInfo": {
"firstname": "Sundar",
"lastname": "v",
"gender": "male",
"country": "Afghanistan",
"state": "Badakhshan",
"city": "Eshkashem",
"pincode": "",
"plancode": "T001",
"userid": 13
},
"roleInfo": {
"defaultphotoid": 94
}
}
],
[
{
"profileInfo": {
"firstname": "ghg",
"lastname": "vbhvh",
"gender": "male",
"state": "Badakhshan",
"city": "Eshkashem",
"pincode": "454",
"plancode": "T001",
"userid": 22
},
"roleInfo": {
"defaultphotoid": 171
}
}
]
]
}
}
}
在上面的json中,我需要将roleInfo.defaultphotoid
移到var image
JS:
$scope.setimage = res.response.data.profilesearchsnippet[0];
for (var i = 0; i++; i<setimage.length; i++){
var image = [];
image .push(setimage[i].roleinfo.defaultphotoid);
}
我分配了一个名为setimage的变量,从那里我试图在另一个数组图像中推送所有defaultphotoid的值来获取所有roleinfos的图像,但我只能获取第一个值。
答案 0 :(得分:1)
这是因为var image = []
在for循环中。它在每个循环后重新初始化。你需要把它放在循环之外
$scope.setimage = res.response.data.profilesearchsnippet[0];
var image = [];
for (var i = 0; i<$scope.setimage.length; i++){
image.push($scope.setimage[i].roleinfo.defaultphotoid);
}
答案 1 :(得分:1)
您可以使用angular.foreach来迭代元素并设置为变量。
var log = [];
angular.forEach(res.response.data.profilesearchsnippet[0], function(value, key) {
this.push(setimage[i].roleinfo.defaultphotoid);
}, log);
答案 2 :(得分:0)
试试这个:
$scope.setimage = res.response.data.profilesearchsnippet;
var images = [];
for (var i = 0; i<$scope.setimage.length; i++){
image.push($scope.setimage[i][0].roleinfo.defaultphotoid);
}
会奏效。