I have an object literal, where the values of its key are more objects, and one of the keys of the inner objects is named "rank" - and has an floating point value. I want to convert the object literal to an array of the inner objects, sorted by the value of "rank".
Input Object:
{
452:{
bla:123,
dff:233,
rank:2
},
234:{
bla:123,
dff:233,
rank:1
}
}
Output Array:
[
{ bla:123, dff:233, rank:1},
{ bla:123, dff:233, rank:2 }
]
Example:
var data = {
foo: {
rank: 5
},
bar: {
rank: 2
},
baz: {
rank: 8
}
};
Javascript:
var mappedHash = Object.keys( data ).sort(function( a, b ) {
return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
return data[ sortedKey ];
});
That would first sort
the inner objects by the value of obj.rank
and after that map
the containing objects into an Array.
Result: [{rank: 2}, {rank: 5}, {rank: 8}]
Reference: Object.keys
, Array.prototype.sort
, Array.prototype.map
The above code contains ECMAscript 262 edition 5 code, which is available in all modern browsers. If you want to support legacy browsers as well, you need to include one of the various ES5-Shim libraries.
Iterate over your object's properties, pushing the inner objects into an array, and then sort the array with a custom sort function:
var inputObject = {}, // your object here
arr = [];
for (var k in inputObject)
arr.push(inputObject[k]);
arr.sort(function(a,b) { return a.rank - b.rank; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With