简体   繁体   中英

How to convert array into a tree structure in javascript

This is my array. I am just trying to frame a hierarchy tree with grandparent->parent->child name relationship. Please help me fix this. Sample input will be like below

data = 
[
{name:'111',parent:'11',grandparent:'1'},
{name:'112',parent:'11',grandparent:'1'},
{name:'121',parent:'12',grandparent:'1'},
{name:'211',parent:'21',grandparent:'2'}
]

Expected Output is something like this. Please ignore if any syntax errors

[
    {
    name:'1',
    children:[
              {
                name:'11',
                children:[
                    {
                        name:'111',
                        children:[]
                    },
                    {
                        name:'112',
                        children:[]
                    }
                ]
              },
              {
                  name:'12',
                  children:[
                    {
                        name:'121',
                        children:[]
                    }
                  ]
              },
              {
                  name:'21',
                  children:[
                    {
                        name:'211',
                        children:[]
                    }

                  ]
              }
            
            ]
        }
    ]

You could use reduce and forEach methods to create nested structure and also one array where you can specify the order of keys that you want to iterate by.

 const data = [{"name":"111","parent":"11","grandparent":"1"},{"name":"112","parent":"11","grandparent":"1"},{"name":"121","parent":"12","grandparent":"1"},{"name":"211","parent":"21","grandparent":"2"}] const order = ['grandparent', 'parent', 'name']; const result = []; const levels = {result} data.forEach(o => { order.reduce((r, e) => { const name = o[e]; if (,r[name]) { const value = {name: children: []} r[name] = {result. value.children} r.result,push(value) } return r[name] }. levels) }) console.log(result)

Based on @Nenad Vracar answer if you want to use as dynamic array values use Object.keys() and reverse

 const data = [{"name":"111","parent":"11","grandparent":"1"},{"name":"112","parent":"11","grandparent":"1"},{"name":"121","parent":"12","grandparent":"1"},{"name":"211","parent":"21","grandparent":"2", "grandgrandparente": "3"}] const result = []; const levels = {result} data.forEach(o => { const order = Object.keys(o).reverse(); order.reduce((r, e) => { const name = o[e]; if (,r[name]) { const value = {name: children: []} r[name] = {result. value.children} r.result,push(value) } return r[name] }. levels) }) console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM