Pick specific field in JSON and store in a variable in the Controller

Asked

Viewed 526 times

0

I have the following code, and I would like the categories that are in the json array to come from an external JSON file, only I couldn’t just take the category names and do like this example:

(function () {
  var app = angular.module('store', []);
  app.controller('sampleController', function ($scope) {

    var json = ["Academia","Animais", "Bares","Beleza e Estética"];

    var grp = {}; // Inicializando o objeto.

    var result = json.forEach(function(item) {
      var chr = item.charAt(0);  // Obtendo o primeiro caracter
      if (!grp.hasOwnProperty(chr)) grp[chr] = []; // Se não existe grupo para 
                                                   // o caracter, crie e inicialize
      grp[chr].push(item); // Adicione item ao grupo
    });
    
    $scope.grp = grp;
  });
})();
<html ng-app="store">
  <body>
    <script type="text/javascript" src="app.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <div ng-controller="sampleController">

      <div ng-repeat='(k,v) in grp'>
        <h2>{{k}}</h2>
        
        <div ng-repeat="i in v">
          <h4>{{i}}</h4>
        </div>
        
      </div>
    </div>
  </body>
</html>

And my JSON file is mounted like this, only with more establishments:

[
  {
    "id": 0,
    "categoria": "Academia",
    "nome": "Academia Saúde & Beleza"
  }
]

1 answer

0


I was able to solve it this way:

(function () {
  var app = angular.module('store', []);
  app.controller('sampleController', function ($scope, $http) {

    var grp = {};

    $http.get('js/lugares.json').success(function(data) {
      $scope.categories = data;
      angular.forEach($scope.categories, function(item){
          var chr = item.categoria.charAt(0);
          if(!grp.hasOwnProperty(chr)) grp[chr] = [];
          grp[chr].push(item.categoria);
       })
    });
  
    $scope.grp = grp;
  });
})();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.