【问题标题】:How to access properties inside an array and push them to a List Angularjs如何访问数组内的属性并将它们推送到列表Angularjs
【发布时间】:2015-06-03 10:10:09
【问题描述】:

我正在开发一个 angularJS 应用程序,我在其中访问服务并获取 JSON 数据,如下所示。

    {  
       "repositoryFileDto":[  
          {   "aclNode":"false",
             "createdDate":"1433166794593",
             "fileSize":"16208",
             "folder":"false",
             "hidden":"false",
             "id":"d4850a7e-17f7-4ee6-a3c5-125c26077da8",
             "lastModifiedDate":"1433166794593",
             "locale":"en",
             "localePropertiesMapEntries":[  ],
             "locked":"false",
             "name":"accountInfo.prpt",
             "ownerType":"-1",
             "path":"/home/admin/accountInfo.prpt",
             "title":"accountInfo",
             "versionId":"1.0",
             "versioned":"true" },
          {  },
          {  }, 
          {  }
       ]

}

从上面的数组中,我需要获取每个对象的名称属性并将它们推送到一个列表中。

这是我的代码,但它说 undefined 不是函数。

 $scope.filteredDashboards = [];
 $scope.ExistingreportDetails = [];
 $scope.GetReportDetails = function() {
            $http({
                method: 'GET',
                url: 'http://192.168.1.201/api/repo/files/%3Ahome%3Aadmin/children?showHidden=false&filter=*',
                // cache: $templateCache,
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                    'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
                    'Authorization': 'Basic YWRtaW46cGFzc3dvcmQ='
                }
            }).
            success(function(data, status) {
                $scope.ExistingreportDetails = angular.toJson(data);
                $scope.filteredDashboards =$scope.ExistingreportDetails[0].repositoryFileDto ;
                console.log($scope.ExistingreportDetails);
                 $scope.filteredDashboards.forEach(function(entry) {
                 console.log(entry);
                 });
             $scope.ExistingreportDetails = $scope.ExistingreportDetails["1"].widgets;
    //alert("success");

            }).
            error(function(data, status) {
                alert("Request failed");
            });
        };

我需要这样的输出,

$scope.reports = 
 [
    {
        name: "AODdetails",
        title: "#f00"
    },
    {
        name: "AccountInfo",
        title: "#0f0"
    }
]

【问题讨论】:

  • 调试您的代码并尝试识别未定义的函数。
  • 您上面的 json 中的颜色和值字段在哪里??
  • 不是颜色和价值,这是我的错误。实际姓名和头衔

标签: json angularjs http controller


【解决方案1】:

看看这个关于按钮点击保存函数的代码将被调用并且值将被存储在报告数组中。

<doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body ng-app="myApp" data-ng-controller="HomeCtrl">


 <button ng-click="save()">Save</button>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

 <script>
   var app = angular.module('myApp',[]);

app.controller('HomeCtrl', function($scope){

    $scope.data= {  
                 "repositoryFileDto":[  
                    {   "aclNode":"false",
                       "createdDate":"1433166794593",
                       "fileSize":"16208",
                       "folder":"false",
                       "hidden":"false",
                       "id":"d4850a7e-17f7-4ee6-a3c5-125c26077da8",
                       "lastModifiedDate":"1433166794593",
                       "locale":"en",
                       "localePropertiesMapEntries":[  ],
                       "locked":"false",
                       "name":"accountInfo.prpt",
                       "ownerType":"-1",
                       "path":"/home/admin/accountInfo.prpt",
                       "title":"accountInfo",
                       "versionId":"1.0",
                       "versioned":"true" },
                    {  "aclNode":"false",
                       "createdDate":"1433166794593",
                       "fileSize":"16208",
                       "folder":"false",
                       "hidden":"false",
                       "id":"d4850a7e-17f7-4ee6-a3c5-125c26077da8",
                       "lastModifiedDate":"1433166794593",
                       "locale":"en",
                       "localePropertiesMapEntries":[  ],
                       "locked":"false",
                       "name":"accountInfo1.prpt",
                       "ownerType":"-1",
                       "path":"/home/admin/accountInfo.prpt",
                       "title":"accountInfo",
                       "versionId":"1.0",
                       "versioned":"true"},
                    {  "aclNode":"false",
                       "createdDate":"1433166794593",
                       "fileSize":"16208",
                       "folder":"false",
                       "hidden":"false",
                       "id":"d4850a7e-17f7-4ee6-a3c5-125c26077da8",
                       "lastModifiedDate":"1433166794593",
                       "locale":"en",
                       "localePropertiesMapEntries":[  ],
                       "locked":"false",
                       "name":"accountInfo2.prpt",
                       "ownerType":"-1",
                       "path":"/home/admin/accountInfo.prpt",
                       "title":"accountInfo",
                       "versionId":"1.0",
                       "versioned":"true"}, 
                    { "aclNode":"false",
                       "createdDate":"1433166794593",
                       "fileSize":"16208",
                       "folder":"false",
                       "hidden":"false",
                       "id":"d4850a7e-17f7-4ee6-a3c5-125c26077da8",
                       "lastModifiedDate":"1433166794593",
                       "locale":"en",
                       "localePropertiesMapEntries":[  ],
                       "locked":"false",
                       "name":"accountInfo3.prpt",
                       "ownerType":"-1",
                       "path":"/home/admin/accountInfo.prpt",
                       "title":"accountInfo",
                       "versionId":"1.0",
                       "versioned":"true" }
                 ]

              };

              $scope.reports=[];

              $scope.save=function()
              {
                for(var i=0; i<$scope.data.repositoryFileDto.length; i++)
                   {
                      var obj1={};
                      obj1.name=$scope.data.repositoryFileDto[i].name;
                      obj1.title=$scope.data.repositoryFileDto[i].title;
                      $scope.reports.push(obj1);
                   } 

                   console.log($scope.reports);
              };


});
</script>
</body>

</html>

【讨论】:

  • TypeError: 无法读取未定义的属性“repositoryFileDto”
  • 那么你的json有问题可能是其他名称而不是repositoryFileD来检查它。对我来说它工作正常。
  • 谢谢 shreya,现在可以了。有没有更好的方法而不运行 for 循环?
  • 如果不运行任何循环,我不确定如何访问数组中的每个对象。
【解决方案2】:

由于$scope.ExistingreportDetails 是一个对象,试试这个:

$scope.filteredDashboards = $scope.ExistingreportDetails.repositoryFileDto[0];

【讨论】:

    【解决方案3】:

    你在哪一行得到错误?

    您可以使用 Angular 的 ForEach 函数来推送对象或数组。 https://docs.angularjs.org/api/ng/function/angular.forEach

      angular.forEach(data.repositoryFileDto[0], function(value) {
        this.push(value);
      }, $scope.ExistingreportDetails);
    

    你已经从你的 HTTP 请求中返回了一个 json 对象,所以在这里转换成一个 json 对象是没有意义的:

    $scope.ExistingreportDetails = angular.toJson(data);
    

    所以如果你想输出“aclNode”的值,你可以简单地做

    console.log(data.repositoryFileDto[0].aclNode);
    

    或者,如果您将数据结果分配给 $scope.ExistingreportDetails :

    console.log($scope.ExistingreportDetails.repositoryFileDto[0].aclNode);
    

    【讨论】:

    • 谢谢,这可行,但我需要推送这些名称和标题属性并创建一个新数组
    【解决方案4】:

    我猜你需要这样使用angular.forEach() 方法:

    试试这个:

    success(function(data, status) {
        $scope.ExistingreportDetails = angular.toJson(data);
    
        console.log($scope.ExistingreportDetails);
    
        angular.forEach($scope.ExistingreportDetails, function(entry, i) {
             $scope.filteredDashboards.push(entry.name); // push the name from the object
        });
    
        $scope.ExistingreportDetails = $scope.ExistingreportDetails["1"].widgets;
        //alert("success");
    })
    

    【讨论】:

    • 正在获取未定义的数组
    【解决方案5】:

    repositoryFileDto 是一个数组,所以:

    $scope.filteredDashboards =$scope.ExistingreportDetails[0].repositoryFileDto[0] ;
    

    编辑:

    $scope.filteredDashboards = $scope.ExistingreportDetails.repositoryFileDto[0];
    

    创建一个新数组:

    var newArray = $scope.filteredDashboards.map(function(el, id, arr){
          return //What you want;
       });
    

    【讨论】:

    • 所以repositoryFileDto 是未定义的。控制台记录它,并显示结果
    • 控制台日志是哪一行?
    • console.log(repositoryFileDto);
    • 它也未定义,我修改了问题请检查
    • 这不是未定义的,只是你必须使用密钥,这里的密钥是 repositoryFileDto 所以用 repositoryFileDto 替换 0
    猜你喜欢
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2019-06-20
    • 1970-01-01
    • 2022-06-13
    • 2023-03-31
    相关资源
    最近更新 更多