0

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?

2 Answers 2

4

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);
      });
Sign up to request clarification or add additional context in comments.

1 Comment

@Zouari - Thanks it worked.Attached the plunker plnkr.co/edit/qC6v8nOP4iFgjlxezTa1?p=preview.How to display only the lecturer value like Doe,Smith,Jones?
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.