I have a javascript object that I want to loop over in angular. The keys in the object are names and the value is a rank. I want to sort the elements by the rank. I tried this which didn't work:
ng-repeat="(name, rank) in topCategories | orderBy: '-rank'"
I also tried without the single quotes around the word "rank". The result is that the elements are looped over but not sorted. No error is logged. Is it possible to sort when iterating over objects?
Example data source:
{
foo: 5,
bar: 7,
baz: 42
}
Edit After inspecting the source code it is easy to see that the orderBy filter simply just returns at once if the supplied argument is an object and not an array. https://github.com/angular/angular.js/blob/master/src/ng/filter/orderBy.js#L68
Having your data structured as just an object has always made it difficult for me to repeat over. I've always needed to convert it to an array of objects first. Rather than having your data as:
{
foo: 5,
bar: 7,
baz: 42
}
Try doing it as an array of objects:
[
{name: 'foo', rank: 5}
{name: 'bar', rank: 7}
{name: 'baz', rank: 42}
]
Then your html is simple:
ng-repeat="result in topCategories | orderBy: '-rank'"
Plunker Example
sources:
Google Groups: Order by object?
Orderby not working with dict syntax on ng-repeat
Has been previously addressed as an issue.
The sources say that orderBy requires an array of objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With