Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display JavaScript Object in a treeview

Is there any tree view component support display any arbitrary JavaScript object like:

{
   foo: 'bar'
   zee: [1, 2, 3]
}

Which result in the following view:

/----foo 
  |   |
  |   |-- 'bar'
  |
  |--zee
      |
      |--
        |--1
        |--2
        |--3

Note the above ascii tree is just for demonstration of the tree structure, not necessarily the final result.

like image 229
Gelin Luo Avatar asked May 06 '26 04:05

Gelin Luo


1 Answers

const Tree=(o,m=o,v='')=>{
    for(e in o){
        if(typeof o!=='object'){console.log(v+'┗╸'+o);return}
        Array.isArray(o)?!Array.isArray(o[e])?console.log(v+(o.length===1||o[e]===o[o.length-1]?'┗╸':'┣╸')+o[e]):Tree(o[e],m,v+(o.length===1||o[e]===o[o.length-1]?' '.repeat(o[e].toString.length+1):'┃'+' '.repeat(e.length))):(console.log(v+(e===Object.keys(m)[0]?'┏╸':Object.keys(o).length===1||Object.keys(o)[Object.keys(o).length-1]===e?'┗╸':'┣╸')+e),Tree(typeof o[e]!=='object'?String(o[e]):o[e],m,v+(Object.keys(o).length===1||Object.keys(o)[Object.keys(o).length-1]===e?' '.repeat(e.length+1):'┃'+' '.repeat(e.length))))
    }
}
//Usage : Tree(YourObjHere)

//Example :
  Tree({
     foo: 'bar',
     zee: [1, 2, 3]
  }) 

//Let me know if bugs
like image 102
Dónde está la biblioteca Avatar answered May 08 '26 17:05

Dónde está la biblioteca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!