简体   繁体   中英

Sort json hierarchy

I have JSON with following structure:

{
   "name":"Scorpiones",
   "children":[
      {
         "name":"Parabuthus",
         "children":[
            {
               "name":"Parabuthus schlechteri"
            },
            {
               "name":"Parabuthus granulatus"
            }
         ]
      },
      {
         "name":"Buthidae",
         "children":[
            {
               "name":"Androctonus",
               "children":[
                  {
                     "name":"Androctonus crassicauda"
                  },
                  {
                     "name":"Androctonus bicolor"
                  }
               ]
            }
         ]
      }
   ]
}

It is required to sort the elements by the name field at each level of the hierarchy. How can this be done with the help of JS?

You can use Object.keys which returns an array contains all object keys, then you can simply sort that array.

 const getSortedKeys = (obj) => { return Object.keys(obj).sort(); }

And to go throw all your object nested keys you can use recursion:

 const trav = (obj) => { if(obj instanceof Array) { // go inside each object in the array obj.forEach(item => trav(item)) } else if(typeof obj === "object") { // sort object keys let keys = getSortedKeys(obj); // do whatevery you want... // go the the next levels keys.forEach(key => trav(obj[key])) } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM