Reputation: 2543
I want to put the information in the following object on the front end using Angular's ng-repeat. I need to order the key/value pairs by value and display them in that order in an array from the top down.
I have the following objects:
{name: 32, name1: 7, name2: 83, name3: 19}
I want to display something on the front end kind of like this:
name2: 83 name: 32 name3: 19 name1: 7
with the key/value pairs sorted in order of the values. I'm sure there is a simple way of doing this but I have yet to perceive it.
Upvotes: 0
Views: 837
Reputation: 17391
You can't sort an object but by converting it into an array you can easily sort it:
var obj = {name: 32, name1: 7, name2: 83, name3: 19};
var pairs = _.pairs(obj);
var sortedPairs = _.sortBy(pairs, function (p) {return -p[1]});
console.log(sortedPairs);
The next step is to show them:
<ul>
<li ng-repeat="item in sortedPairs">
{{item[0]}}: {{item[1]}}
</li>
</ul>
Upvotes: 2