Created
December 20, 2023 07:50
-
-
Save kfitfk/1405d370d1a1384b2a17028b581bd224 to your computer and use it in GitHub Desktop.
parse JSON string and keep the props in alphabetic order
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 sortObjectAlphabetically(obj) { | |
if (typeof obj !== 'object' || obj === null) { | |
// Base case: obj is not an object, or is null | |
return obj; | |
} | |
if (Array.isArray(obj)) { | |
// If obj is an array, recursively sort its elements | |
return obj.map((element) => sortObjectAlphabetically(element)); | |
} | |
// If obj is an object, recursively sort its properties | |
const sortedObject = {}; | |
Object.keys(obj).sort().forEach((key) => { | |
sortedObject[key] = sortObjectAlphabetically(obj[key]); | |
}); | |
return sortedObject; | |
} | |
// Your JSON string | |
const jsonString = '{"c": 3, "a": 1, "b": {"d": 4, "e": 5}}'; | |
// Parse JSON string into a JavaScript object | |
const jsonObject = JSON.parse(jsonString); | |
// Sort the entire object alphabetically | |
const sortedObject = sortObjectAlphabetically(jsonObject); | |
// Display the result | |
console.log(sortedObject); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment