Iterate through nested json array in angular controller and get unique values

前端 未结 5 644
Happy的楠姐
Happy的楠姐 2020-12-31 08:17

I need to iterate through nested json array which looks like that

[
  {
    \"title\": \"EPAM\",
    \"technologies\": [
        \"PHP\",
        \".net\",
          


        
相关标签:
5条回答
  • 2020-12-31 08:54

    try this

    var app = angular.module('app', []);
    
    app.controller('CompaniesController', ['$scope', '$http', 
      function($scope, $http) {
        $http.get('json/companies.json').success(function(data) {
            $scope.companies = data; // get data from json
    
            $scope.techStack = []
    
            angular.forEach($scope.companies, function(item){
                $scope.techStack = item.technologies;
                var uniqueTech = [];
                for (var i = 0; i < $scope.techStack.length; i++)
                {
                    if (uniqueTech.indexOf($scope.techStack[i]) == -1)
                        uniqueTech.push($scope.techStack[i]);
                }   
                console.log("Unique Technologies : " + uniqueTech);
    
            })
        });
    
      }
    ]); 
    
    0 讨论(0)
  • 2020-12-31 08:59

    Use angular's forEach:

     var app = angular.module('app', []);
        app.controller('CompaniesController', ['$scope', '$http', 
          function($scope, $http) {
            $http.get('json/companies.json').success(function(data) {
                $scope.companies = data; // get data from json
                  angular.forEach($scope.companies, function(item){
                       console.log(item.technologies);  
                   })
                });
            });
    
          }
        ]); 
    
    0 讨论(0)
  • 2020-12-31 09:07

    In order to loop through array in AngularJS, you can simply use angular.forEach. For example,

    angular.forEach(companiesList, function(company) {
        //Here you can access each company.
    });
    

    I have made a simple demo based on your code that list "Companies" and unique "Technologies".

    DEMO

    0 讨论(0)
  • 2020-12-31 09:10

    user angular's foreach function for looping through data.

    0 讨论(0)
  • 2020-12-31 09:13

    If you need only to display nested array on UI, you can do that straight in view e.g.

                <tr ng-repeat="i in Items">
                    <td valign="top">{{i.Value}}</td>
                    <td valign="top">
                        <table>
                            <tr ng-repeat="c in i.Children">
                                <td>{{c.Value}}</td>
                            </tr>
                        </table>
                    </td>
                </tr>
    
    0 讨论(0)
提交回复
热议问题