kuba0506
kuba0506

Reputation: 475

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.

Upvotes: 5

Views: 7695

Answers (2)

a8m
a8m

Reputation: 9474

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}

Upvotes: 5

user1907906
user1907906

Reputation:

An array has no named keys. It has integers as position. So don't use toArray.

Upvotes: 0

Related Questions