Today I had to output a tree like object structure in JavaScript. Initially, I came up with this code:
// for spacing
const tab = ( num ) => {
let tab = " "
if ( num === 0 ) {
return ''
}
for (let i=1; i < num; i++) {
tab += tab
}
return tab
}
// displaying
const display_directory = ( node, depth = 0 ) => {
for ( let n in node ) {
console.log(`${tab(depth)}${in}`)
if ( Object.keys( node[ in ] ).length > 0 ) {
display_directory( node[ in ], depth+1 )
}
}
}
It works perfectly fine, but the issue is that the order of names is going to be random as Object is not sorted. After some moments, I came up with a very simple solution to display name in alphabetical order.
const display_directory = ( node, depth = 0 ) => {
let keys = Object.keys(node).sort()
for ( let key of keys ) {
console.log(`${tab(depth)}${key}`)
if ( Object.keys( node[ key ] ).length > 0 ) {
display_directory( node[ key ], depth+1 )
}
}
}