Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS toArray converts object keys to numbers

I use angular-filter in my project to sort the output objects by page the problem is when I use syntax like this:

<ul class="catalog-list"
    ng-repeat="(key, value) in list | groupBy: 'styl' | toArray | orderBy:'page'">

  {{key}}

  <li ng-repeat="dziecko in value | filter:search | bookmark:search" 
      ng-class="{active:isActiveTab(dziecko)}"
      ng-click="openItem(dziecko)">
    {{dziecko.rodzina}}
    <b>{{dziecko.page}}</b>
  </li>
</ul>

Angular converts 'styl' properties ['nowoczesny','klasyczny'..] to numbers. Sorting works fine but I want to obtain names instead of numbers.

like image 428
kuba0506 Avatar asked Dec 15 '14 11:12

kuba0506


1 Answers

groupBy return an object, and orderBy expect array as an argument, so that's the reason you should use toArray filter.

toArray work like that:
Usage: object | toArray: addKey[optional]
if addKey set to true, the filter also attaches a new property $key to the value containing the original key that was used in the object we are iterating over to reference the property

So, you can do something like this example, or take a look on the jsbin

JS:

$scope.groups = [
    { category: 'alpha', id: 2 },
    { category: 'beta',  id: 3 }, 
    { category: 'gamma', id: 0 },
    { category: 'alpha', id: 4 },
    { category: 'beta',  id: 5 }, 
    { category: 'gamma', id: 1 }
   ];

HTML:

 <ul ng-repeat="group in groups | groupBy:'category' | toArray:true | orderBy:min">
    <!-- print the group name -->
    <li>{{ group.$key }}</li>
    <!-- iterate over the group members and order each group by id -->
    <li ng-repeat="item in group | orderBy:'id'">
      {{ item }}
    </li>
</ul>

RESULT:

  • alpha
  • {"category":"alpha","id":2}
  • {"category":"alpha","id":4}

  • beta

  • {"category":"beta","id":3}
  • {"category":"beta","id":5}

  • gamma

  • {"category":"gamma","id":0}
  • {"category":"gamma","id":1}
like image 153
a8m Avatar answered Sep 27 '22 22:09

a8m