Possible Duplicate:
Sorting JavaScript Object by property value
I want to get the top results for some value within my JSON. Easier explained with the example:
var jsonData = {
bom: [
{
"Component":"Some Thing",
"Version":"Version ABC",
"License":"License ABC",
},
{
"Component":"Another Thing",
"Version":"Version XYZ",
"License":"License ABC",
},
etc ....
]
}
So my goal is to determine that “License ABC” or another has X number of occurrences and then I want to be able sort those key:val pairs to insert into into the DOM as “The top X most popular licenses are:
- License ABC – 100
- License XYZ – 70
- License 123 – 25
Right now I have this:
var countResults = function() {
var fileLicenses = [];
for ( var i = 0, arrLen = jsonData.files.length; i < arrLen; ++i ) {
fileLicenses.push(jsonData.files[i]["License"]);
}
keyCount = {};
for(i = 0; i < fileLicenses.length; ++i) {
if(!keyCount[fileLicenses[i]]) {
keyCount[fileLicenses[i]] = 0;
}
++keyCount[fileLicenses[i]];
}
console.log( keyCount );
}();
Which get’s me most of what I want, an object with key : values
{
thisKey : 78,
thatKey :125,
another key : 200,
another key : 272,
another key : 45,
etc ...
}
But I don’t know how to do anything with that. I just need to sort the numeric right column and have the associated keys stay along for the ride. Thoughts? Thank you!
You can’t sort an object by it’s values. What you can do is to transform it to an array of objects and sort that instead. Something like:
Usage:
/code not tested