Search code examples
jqueryarraysjsonalphabetical-sort

How can I put array alphabetically in json?


I have the following json structure.

json = {
        "Canada": ["Toronto"],
        "Argentina": ["Buenos Aires"],
        "Brazil": ["Rio de Janeiro"],
        }

I'm looking for a way to sort alphabetically by the children. It would be like this:

json = {
        "Argentina": ["Buenos Aires"],
        "Brazil": ["Rio de Janeiro"],
        "Canada": ["Toronto"]

        }

Can someone give me a hand? I'm using jQuery.


Solution

  • Sort object keys then build the object again with the new order of keys but with the same values :

    Object.keys(json) // extract object keys in an array
       .sort()  // sort keys' array alphabetically 
       .reduce((result, key) => ({...result, [key]: json[key]}), {}) // build the same object but with the new order of keys