OK, as you may know, javascript has sort() function, to sort arrays, but nothing for object...
So in that case, we need to somehow get array of the keys and sort them, thats the reason the apis gives you objects in an array most of the time, because Array has more native functions to play with them than object literal, anyway, the quick solotion is using Object.key which return an array of the object keys, I create the ES6 function below which does the job for you, it uses native sort() and reduce() functions in javascript:
function sortObject(obj) {
return Object.keys(obj)
.sort().reduce((a, v) => {
a[v] = obj[v];
return a; }, {});
}
And now you can use it like this:
let myObject = {a: 1, c: 3, e: 5, b: 2, d: 4};
let sortedMyObject = sortObject(myObject);
Check the sortedMyObject and you can see the result sorted by keys like this:
{a: 1, b: 2, c: 3, d: 4, e: 5}
Also this way, the main object won't be touched and we actually getting a new object.
I also create the image below, to make the function steps more clear, in case you need to change it a bit to work it your way:
Object.entries
-based answer which is the cleanest and most readable state of the art since ES2017: stackoverflow.com/a/37607084/245966 – jakub.g