Error with duplicate values in Angularjs

Asked

Viewed 434 times

2

I have a problem of duplicate values in Angularjs, in my JSON will always have repeated categories, in ng-repeat I used the track by $index but the error persisted.

The code of my controller:

angular.module('starter').controller('Guia', 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;
});

My HTML is like this:

<div class="list" ng-repeat="(k,v) in grp track by $index">
  <div class="item item-divider">{{k}}</div>
  <a ng-href="#/categoria-guia" class="item" ng-repeat="i in v">{{i}}</a>
</div>

And the JSON so:

[
  {
    "id": 0,
    "nome": "Agência MegaDigital",
    "categoria": "Tecnologia e Informática"
  },
  {
    "id": 1,
    "nome": "Bar do Grego",
    "categoria": "Bares e Restaurantes"
  },
  {
    "id": 2,
    "nome": "Anselmo Lanches",
    "categoria": "Bares e Restaurantes"
  },
  {
    "id": 3,
    "nome": "Internet de Dimas",
    "categoria": "Tecnologia e Informática"
  },
  {
    "id": 4,
    "nome": "Banca Caixa Postal",
    "categoria": "Banca de Revista"
  },
  {
    "id": 5,
    "nome": "Xerox Central",
    "categoria": "Papelaria e Escritório"
  }
]

The final result displays a list of all categories in a list sorted by the initial category letter.

  • The only problem you’re having is sorting by the initial letter?

  • No, in relation to sorting I have already managed to do and it’s all right, the problem is that as I have repeated categories, this error appears here: [ngRepeat:dupes] Duplicates in a Repeater are not allowed. Use 'track by' Expression to specify Unique Keys.

1 answer

1


Altemberg, from what I can see, you’re using an object var grp = {}; that has an array grp[chr] = [].

You created in the object grp, a key b that receives the category within an array, would result in something like this:

 grp = {
     b: ["Banca de Revista", "Bares e Restaurantes"], // ** Array **
     p: ["Papelaria e Escritório"],
     t: ["Tecnologia e Informática"]
 }

So far so good, now let’s solve the problem of repetition:

 if(grp[chr].indexOf(item.categoria) === -1) grp[chr].push(item.categoria)
 // Só acrescentar o novo valor se ele ainda não existir

Working:

var app = angular.module('myApp', [])

app.controller('myCtrl', function($scope, $http) {
  var grp = {}; 
  var data = [{
    "id": 0,
    "nome": "Agência MegaDigital",
    "categoria": "Tecnologia e Informática"
  }, {
    "id": 1,
    "nome": "Bar do Grego",
    "categoria": "Bares e Restaurantes"
  }, {
    "id": 2,
    "nome": "Anselmo Lanches",
    "categoria": "Bares e Restaurantes"
  }, {
    "id": 3,
    "nome": "Internet de Dimas",
    "categoria": "Tecnologia e Informática"
  }, {
    "id": 4,
    "nome": "Banca Caixa Postal",
    "categoria": "Banca de Revista"
  }, {
    "id": 5,
    "nome": "Xerox Central",
    "categoria": "Papelaria e Escritório"
  }];
  $scope.categories = data; 
  angular.forEach($scope.categories, function(item) {
    var chr = item.categoria.charAt(0);
    if (!grp.hasOwnProperty(chr)) grp[chr] = []; // Criando uma chave no OBJETO (chr), e essa chave possui um ARRAY
    if(grp[chr].indexOf(item.categoria) === -1) grp[chr].push(item.categoria); // Ainda utilizando o array
  })
  $scope.grp = grp;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div class="list" ng-repeat="(k,v) in grp">
    <div class="item item-divider">{{k}}</div>
    <br>
    <a ng-href="#/categoria-guia" class="item" ng-repeat="i in v">{{i}}<br></a>
  </div>
</div>

  • Samir, the following error appeared: [orderby:notarray] Expected array but Received: {} ?

  • @Altembergandrade, you look much better.

  • I’ve already done the editing, take a look there please.

  • @Altembergandrade, look at the issue, see if it’s clear

  • Let me be quite honest, I got a little lost in relation to the object and the array. How can I put ng-repeat in the grp[Chr] array like you said? I’m sorry if this seems like something very simple or obvious, but is that I just finished an angle book a little bit and I’m trying to create an application to go studying and putting everything into practice.

  • @Altembergandrade, Look at the edition, now it is working... I imagine that now it was rsrs. Sorry for the delay, I was a little busy. It was something very simple, I believe I was getting in the way before.

  • 1

    Now it was! And I managed to understand the code better now kkkk. Thank you very much, Samir.

Show 2 more comments

Browser other questions tagged

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