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