Get specific field in JSON and store in a variable on Controller

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, but I just could not get the names of the categories and do 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><divng-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 outlets:

[
  {
    "id": 0,
    "categoria": "Academia",
    "nome": "Academia Saúde & Beleza"
  }
]
    
asked by anonymous 27.07.2016 / 16:04

1 answer

0

I was able to resolve it as follows:

(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;
  });
})();
    
27.07.2016 / 23:09