Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]))
    }
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!