I have been struggling to find a helpful resource given the peculiar nature of my object... I would like to simply sort an object alphabetically however I need to sort by my key.
here is an example object with the same schema of the object I am working with
{
"sections": [
{
"title": "21Q4 Results",
"states": {
"Maine": {
"string1":[{stuff1}],
"string2":[{stuff2}],
},
"Arkansas": {
"string1":[{stuff1}],
"string2":[{stuff2}],
},
"Kentucky": {
"string1":[{stuff1}],
"string2":[{stuff2}],
},
}
}
]
}
The goal is to arrange the sections.states in alphabetical order. Unfortunately, the structure of this object is generated by an API which I have no control over, so changing the structure from the backend is not really an option.
What is the best way to achieve this? Any help would be greatly appreciated.
Here is a way to convert the states object into a sorted array in order to preserve a sort order.
let stuff1 = stuff2 = 'foobar'
let data = {
"sections": [{
"title": "21Q4 Results",
"states": {
"Maine": {
"string1": [{ stuff1 }], "string2": [{ stuff2 }],
},
"Arkansas": {
"string1": [{ stuff1 }], "string2": [{ stuff2 }],
},
"Kentucky": {
"string1": [{ stuff1 }], "string2": [{ stuff2 }],
},
}
}]
}
let newstates = Object.keys(data.sections[0].states).sort((a, b) => a.localeCompare(b)).map(s => ({state: s, data: data.sections[0].states[s] }));
console.log(newstates)