Skip to content

Instantly share code, notes, and snippets.

@kfitfk
Created December 20, 2023 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kfitfk/1405d370d1a1384b2a17028b581bd224 to your computer and use it in GitHub Desktop.
Save kfitfk/1405d370d1a1384b2a17028b581bd224 to your computer and use it in GitHub Desktop.
parse JSON string and keep the props in alphabetic order
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