{
"TR":{
"total_fans":1848,
"country_name":"Turkey"
},
"US":{
"total_fans":1097,
"country_name":"United States"
},
"DE":{
"total_fans":915,
"country_name":"Germany"
},
"MX":{
"total_fans":1148,
"country_name":"Mexico"
},
"RS":{
"total_fans":359,
"country_name":"Serbia"
},
"IT":{
"total_fans":798,
"country_name":"Italy"
}
}
I would like to sort this based on fans. For instance, in this case it should be "TR", "MX", "US"... and so on using JS and Underscore if that helps. Thanks!
JavaScript objects are unordered, so you won't be able to sort or otherwise define a specific order.
You could convert the properties to an Array, and sort that instead, but that's about as close as you'll get.
Since it seems you want to sort by number of fans, you can do this.
Object.keys(myObject)
.sort(function(a,b) {
return myObject[a].total_fans - myObject[b].total_fans;
}).forEach(function(key) {
console.log(myObject[key]);
});
To support IE8 and lower, you'll need patches for Object.keys and Array.prototype.forEach.
And as Bruce Lim noted, this is an ascending sort. To descend, swap the operands of the - operator after the return.
return myObject[b].total_fans - myObject[a].total_fans;
No underscore is necessary if you don't care about IE < 9. Given your structure being in a variable obj:
var sorted = Object
.keys(obj)
.map(function(key) {
// Put the country in the item?
obj[key].country = key;
return obj[key];
})
.sort(function(a, b) {
if (a.total_fans > b.total_fans) {
return -1;
} else if (b.total_fans > a.total_fans) {
return 1;
}
return 0;
});
This will give you an Array sorted with the items having the most fans being first, and the country code added to each item in case you need that (omit if unnecessary).
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