Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda