Skip to content

Instantly share code, notes, and snippets.

@ninapavlich
Last active April 19, 2024 09:02
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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