简体   繁体   中英

How to loop through an array within an object

I have JSON output in the below format.{

data{
  "id" : 1,
  "age":20,
  "subjects":[
    {"code":"101", "Lecturer":"Doe"}, 
    {"code":"102", "Lecturer":"Smith"},
    {"code":"103", "Lecturer":"Jones"}
  ]
}

I tried the following code to loop through subjects from data object.

$scope.values=[];
angular.forEach(data.subjects,function(value,key){
  $scope.values.push(value.Lecturer);
});

I don't see any values in data.subjects in forEach loop to iterate.What elsei am missing in the code?

Sorry but you Json is not well formed . i am quiet sure it is due to the name of your data. If it is var data ={ ... }; or var data = {data : {...} }. For the first case it should be something like this

var data = {
    "id": 1,
    "age": 20,
    "subjects": [{
      "code": "101",
      "Lecturer": "Doe"
    }, {
      "code": "102",
      "Lecturer": "Smith"
    }, {
      "code": "103",
      "Lecturer": "Jones"
    }]
  };

  $scope.values = [];
  angular.forEach(data.subjects, function(value, key) {
    $scope.values.push(value.Lecturer);
  });
  console.log($scope.values);

If you are having something like this var data = {data : {...}}. Just add data.data.subjects to your forEach

angular.forEach(data.data.subjects, function(value, key) {
        $scope.values.push(value.Lecturer);
      });

I think you are missing a colon (:) after data.

data: {
  "id" : 1,
  "age":20,
  "subjects":[
    {"code":"101", "Lecturer":"Doe"}, 
    {"code":"102", "Lecturer":"Smith"},
    {"code":"103", "Lecturer":"Jones"}
  ]
}

This is working for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM