0

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.

  • 4
    Possible duplicate of [Is there a way to sort/order keys in JavaScript objects?](https://stackoverflow.com/questions/9658690/is-there-a-way-to-sort-order-keys-in-javascript-objects) – Taplar Oct 31 '17 at 18:24

1 Answers1

0

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
Abdennour TOUMI
  • 64,884
  • 28
  • 201
  • 207