Skip to content
Advertisement

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:[]
                    }

                  ]
              }
            
            ]
        }
    ]

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement