CodeClimber
CodeClimber

Reputation: 4191

How to order a dictionary by value in AngularJS

I've a REST api that returns the list of locales as dictionary:

{
"en-uk": "English UK",
"en-us": "English USA",
...
}

This dictionary is correctly ordered alphabetically by value.

When AngularJS receives it via HTTP, the dictionary gets automatically re-sorted by key, so when I bind to a select element the list of options is ordered by key, and the alphabetical order by key doesn't match the one by value, I get a wrong sorting.

The problem I suppose is due to the fact that such dictionary becomes basically one object with 800+ properties. How do I sort it by value?

Upvotes: 3

Views: 1745

Answers (4)

M G
M G

Reputation: 1

Seen this when the key is numerical. If the key's data type is string than it would keep its sorted state after an API call. If the key's data type is numerical, than, you would need set the key's value as a string and even add single quotes before and after the key's value, before the API sends it back.

I haven't tried the approach to stringfy the dictionary in the API. After the call you would parse the string back to an object with something like JSON.parse(string) might be your best bet.

Upvotes: 0

CodeClimber
CodeClimber

Reputation: 4191

The problem is indeed you cannot sort the values of the properties of an object. So I convert it to an array before binding it:

So,

languageResource.getCultures().then(function(cultures) {   
       vm.availableCultures = cultures;
});

becomes

languageResource.getCultures().then(function (culturesDictionary) {
                        var cultures = [];
                        angular.forEach(culturesDictionary, function (value, key) {
                            cultures.push({
                                lcid: key,
                                name: value
                            });
                        });
                        vm.availableCultures = cultures;
                    });

Upvotes: 0

Abhishek Singh
Abhishek Singh

Reputation: 2727

You can modify the way you send the response from the server. Instead of sending the response as an object, send the stringified object.

Upvotes: 0

I. Ahmed
I. Ahmed

Reputation: 2534

First: You have to find all keys.

Second: Iterate all the keys.

Third: Then sort the array with values.

Please use the following:

let obj = {
"en-us": "English USA",
"en-uk": "English UK"
};

// Get an array of the keys:
let keys = Object.keys(obj);

// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] > obj[b] });

console.log(keys);
console.log(obj[keys[0]]);

Upvotes: 2

Related Questions