Sorting JSON Objects
Sorting JSON Objects for use in ordered selects, data, etc.
by ctoestreich
HTML
Unsorted: <span id="unsorted"></span>
<p />Sorted Values: <span id="sortedByValues"></span>
<p />Sorted Keys: <span id="sortedByKeys"></span>
<p />Unsorted: <select id="selectUnsorted"></select>
<p />Sorted Values: <select id="selectSortedByValues"></select>
<p />Sorted Keys: <select id="selectSortedByKeys"></select>
JavaScript
var object = {
b: 'y',
c: 'x',
a: 'z',
d: 'w',
e: '1'
};
document.getElementById('unsorted').innerText = JSON.stringify(object);
document.getElementById('sortedByValues').innerText = JSON.stringify(sortByValues(object));
document.getElementById('sortedByKeys').innerText = JSON.stringify(sortByKeys(object));
_.each(object, function(o,i){
var select = document.getElementById('selectUnsorted');
select.options[select.options.length] = new Option(i, o[i]);
});
_.each(sortByValues(object), function(o,i){
var select = document.getElementById('selectSortedByValues');
select.options[select.options.length] = new Option(o[0], o[1]);
});
_.each(sortByKeys(object), function(o,i){
var select = document.getElementById('selectSortedByKeys');
select.options[select.options.length] = new Option(o[0], o[1]);
});
function sortByValues(object){
return sort(object, 1);
}
function sortByKeys(object){
return sort(object, 0);
}
function sort(object, index) {
index = index || 0;
return _.chain(object).map(function (value, key) {
return [key, value];
}).sortBy(function (tuple) {
return tuple[index] === "" ? 0 : tuple[index];
}).value();
}