将值从json推送到数组中

时间:2016-12-26 07:59:54

标签: angularjs json

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的图像,但我只能获取第一个值。

3 个答案:

答案 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);

https://docs.angularjs.org/api/ng/function/angular.forEach

答案 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);
}

会奏效。