Last active
August 23, 2024 07:37
-
-
Save ninapavlich/1697bcc107052f5b884a794d307845fe to your computer and use it in GitHub Desktop.
Deep Sort Javascript Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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