Reputation: 2424
is it possible to get a key by it's order. I have a data model that has changing keys.
for example
{A: 1, k:2}
it will change at some point but the order will be the same.. For example
{J: 1, F:2}
Is there a way to to get the properties by it's order (first, second)??
Upvotes: 0
Views: 53
Reputation: 147343
Just to build on what Patrick posted, you can create an index of the keys sorted by their values:
var obj = {A: 1, k:7, q:0, z:4};
var index = Object.keys(obj).sort(function(a, b) {
return obj[a] - obj[b];
});
// Keys sorted by value
console.log(index.join()); // q,A,z,k
// Get 2nd highest value
console.log(obj[index[1]]) // 1
// Get highest value
console.log(obj[index[index.length - 1]]) // 7
You could also create an object of value:key pairs, provided that value.toString()
returns a unique value:
// Create a reversed object of value:key
var revObj = Object.keys(obj).reduce(function(newObj, key){
newObj[obj[key]] = key;
return newObj;
}, {});
console.log(JSON.stringify(revObj)); // {"0":"q","1":"A","4":"z","7":"k"}
Note that in some browsers, the keys are sorted by numeric value, not the order they are added to revObj (or any other particular order).
Upvotes: 0
Reputation: 1559
A dictionary has no order, so what you can do is convert it to an array of pairs, sort it and then iterate over it.
var arr = {A:300, B:60, C:200}
var sortable = [];
for (var el in arr)
sortable.push([el, arr[el]])
sortable.sort(function(a, b) {return a[1] - b[1]})
//[["B", 60], ["C", 200], ["A", 300],
Upvotes: 3
Reputation: 232
If you store your key-value pairs in the opposite order, with the number as the key and the letter as the property, then you will be able to get the order you desire.
Upvotes: 0