简体   繁体   English

如何遍历对象内的数组

[英]How to loop through an array within an object

I have JSON output in the below format.{ 我有以下格式的JSON输出。{

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? 我在forEach循环中的data.subjects中没有看到要迭代的值。代码中还缺少其他什么?

Sorry but you Json is not well formed . 抱歉,但您Json身体不好。 i am quiet sure it is due to the name of your data. 我非常确定这是由于您的数据名称所致。 If it is var data ={ ... }; 如果是var data = {...}; or var data = {data : {...} }. 或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 : {...}}. 如果您有类似var data = {data:{...}}的内容。 Just add data.data.subjects to your forEach 只需将data.data.subjects添加到您的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. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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