Object keys and values in Javascript have no intrinsic order. Before you can sort them into a desired order, you need to store them in an ordered structure.
Let's get the items into an Array
, which does have intrinsic order:
var object = {
a: 1,
b: 5,
c: 2
}
var keyValues = []
for (var key in object) {
keyValues.push([ key, object[key] ])
}
The keyValues
array now holds ['a', 1], ['b', 5], ['c', 2]
. Let's sort this array, using the second value in each pair for comparison:
keyValues.sort(function compare(kv1, kv2) {
// This comparison function has 3 return cases:
// - Negative number: kv1 should be placed BEFORE kv2
// - Positive number: kv1 should be placed AFTER kv2
// - Zero: they are equal, any order is ok between these 2 items
return kv1[1] - kv2[1]
})
Now keyValues
is sorted from lesser to greater. Note that you can't convert it back to an object, or the order will be lost.