Reputation: 4818
I have an object like:
json_result = {X: 0.42498, A: 0.34891, B: 0.38408, C: 0.22523}
I want to sort the above in descending order of values, i.e.,
json_result = {X: 0.42498, B: 0.38408, A: 0.34891, C: 0.22523}
I am thinking something like:
for ( key in json_result)
{
for ( value1 in json_result[key])
{
for (value2 in json_result[key])
{
}
}
}
Is there any other way around?
Upvotes: 2
Views: 1508
Reputation: 14257
As mentioned in the comments, object key order isn't guaranteed, so sorting your object wouldn't make much sense. You should use an Array as a result.
var json_result = {X: 0.42498, A: 0.34891, B: 0.38408, C: 0.22523};
function sort(obj) {
return Object.keys(obj).sort(function(a, b) {
return obj[b] - obj[a];
});
}
var sorted = sort(json_result);
console.log('sorted keys', sorted);
console.log('key lookup', sorted.map(function(key) {
return json_result[key]
}));
console.log('sorted objects', sorted.map(function(key) {
return {[key]: json_result[key]}
}));
Upvotes: 3
Reputation: 16779
You can't "sort" the keys of an object, because they do not have a defined order. Think of objects as a set of key-value pairs, rather than a list of them.
You can, however, turn your JSON into a sorted list (array) of key-value pairs, yielding an object that looks like this:
[ ['X', 0.42498], ['B', 0.38408], ['A', 0.34891], ['C', 0.22523] ]
var result = {X: 0.42498, A: 0.34891, B: 0.38408, C: 0.22523}
var sorted = Object.keys(result).map(function (key) {
return [key, this[key]]
}, result).sort(function (a, b) {
return b[1] - a[1]
})
console.log(sorted)
.as-console-wrapper { min-height: 100vh; }
Upvotes: 2