Skip to content

Instantly share code, notes, and snippets.

@ninapavlich
Last active August 23, 2024 07:37
Show Gist options
  • Save ninapavlich/1697bcc107052f5b884a794d307845fe to your computer and use it in GitHub Desktop.
Save ninapavlich/1697bcc107052f5b884a794d307845fe to your computer and use it in GitHub Desktop.
Deep Sort Javascript Object
function sortObject(object) {
//Thanks > http://whitfin.io/sorting-object-recursively-node-jsjavascript/
if (!object) {
return object;
}
const isArray = object instanceof Array;
var sortedObj = {};
if (isArray) {
sortedObj = object.map((item) => sortObject(item));
} else {
var keys = Object.keys(object);
// console.log(keys);
keys.sort(function(key1, key2) {
(key1 = key1.toLowerCase()), (key2 = key2.toLowerCase());
if (key1 < key2) return -1;
if (key1 > key2) return 1;
return 0;
});
for (var index in keys) {
var key = keys[index];
if (typeof object[key] == 'object') {
sortedObj[key] = sortObject(object[key]);
} else {
sortedObj[key] = object[key];
}
}
}
return sortedObj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment