Last active
March 8, 2023 04:39
-
-
Save elad-yosifon/300b89ec5479b9b712b7 to your computer and use it in GitHub Desktop.
JSON object sort by key - recursive
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
/** | |
* this is a utility. | |
* should NOT be used in production! | |
*/ | |
function sortJSON(object) { | |
if (object instanceof Array) { | |
for (var i = 0; i < object.length; i++) { | |
object[i] = sortJSON(object[i]); | |
} | |
return object; | |
} else if (typeof object != "object") return object; | |
var keys = Object.keys(object); | |
keys = keys.sort(); | |
var newObject = {}; | |
for (var i = 0; i < keys.length; i++) { | |
newObject[keys[i]] = sortJSON(object[keys[i]]) | |
} | |
return newObject; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment