NIKHIL RANE
NIKHIL RANE

Reputation: 4110

How to create a tree of existing json

I want to parse a json that is fetch from api

I have following schema

nodes = [
    {
        id: 1,
        name: 'root1',
        key: 'value1'
        key1: 'value2'
        children: [
            { id: 2, name: 'child1' },
            { id: 3, name: 'child2' }
        ]
    },
    {
        id: 4,
        name: 'root2',
        key3: 'value3'
        key4: 'value4'
        children: [
            { id: 5, name: 'child2.1' },
            {
                id: 6,
                name: 'child2.2',
                key5: 'value5'
                key6: 'value6'
                children: [{
                    id: 7,
                    name: 'subsub',
                    children: [{
                        id: 8,
                        name: 'subsubsub'
                    }]
                }]
            }
        ]
    }
];

I'm trying following but not working

data = []

var nodesFun = function(n, data, cObj) {
    let obj = {}
    obj["name"] = n['name']
    if (n['children']) {
        console.log(obj);
        console.log("name--> "+n['name']);
        let childList = []
        for (let i=0; i < n['children'].length; i++){
            console.log("cname--> "+n['children'][i]['name']);
            childList.push({"name": n['children'][i]['name']})
            let dataObj = nodesFun(n['children'][i], data, obj)
            if (dataObj){
                data.push(dataObj)
            }
        }
        obj["children"] =  childList
        cObj["children"] =  obj
        return cObj
    }else{
      cObj["children"] =  obj
      return cObj
    }
}
nodesFun(nodes, data, {})
console.log(nodes);

Now I want to convert above json in following format using recursive function

nodes = [{
        id: 1,
        name: 'root1',
        children: [
            { id: 2, name: 'child1' },
            { id: 3, name: 'child2' }
        ]
    },
    {
        id: 4,
        name: 'root2',
        children: [
            { id: 5, name: 'child2.1' },
            {
                id: 6,
                name: 'child2.2',
                children: [{
                    id: 7,
                    name: 'subsub',
                    children: [{
                        id: 8,
                        name: 'subsubsub'
                    }]
                }]
            }
        ]
    }
];

Upvotes: 0

Views: 92

Answers (2)

Hassan Imam
Hassan Imam

Reputation: 22524

You can modify your original nodes array using array#forEach and recursive approach. Iterate through each key of node if the key includes key word delete it and if it contains children call deleteKey function again.

var nodes = [ { id: 1, name: 'root1', key: 'value1', key1: 'value2', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { id: 4, name: 'root2', key3: 'value3', key4: 'value4', children: [ { id: 5, name: 'child2.1' }, { id: 6, name: 'child2.2',key5: 'value5', key6: 'value6', children: [{ id: 7, name: 'subsub', children: [{ id: 8, name: 'subsubsub' }] }] } ] } ];

var deleteKey = (nodes) => {
  nodes.forEach(node => {
    Object.keys(node).forEach(k => {
      if(k.includes('key'))
        delete node[k];
      if(k == 'children')
        deleteKey(node[k]);
    })
  });
}
deleteKey(nodes);
console.log(nodes);
.as-console-wrapper { max-height: 100% !important; top: 0; }

In case you want a new array, you can use array#reduce and array#map.

var nodes = [ { id: 1, name: 'root1', key: 'value1', key1: 'value2', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { id: 4, name: 'root2', key3: 'value3', key4: 'value4', children: [ { id: 5, name: 'child2.1' }, { id: 6, name: 'child2.2',key5: 'value5', key6: 'value6', children: [{ id: 7, name: 'subsub', children: [{ id: 8, name: 'subsubsub' }] }] } ] } ];

var removeKey = (nodes) => {
  return nodes.map(node => {
    return Object.keys(node).reduce((r, k) => {
      if(!k.includes('key'))
        r[k] = node[k];
      if(k == 'children')
        r[k] = removeKey(node[k]);        
      return r;
    },{});
  });
}
console.log(removeKey(nodes));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

ggirodda
ggirodda

Reputation: 780

The function delete all the keys that are not id, name and children from your object

let nodes = [
    {
        id: 1,
        name: 'root1',
        key: 'value1',
        key1: 'value2',
        children: [
            { id: 2, name: 'child1' },
            { id: 3, name: 'child2' }
        ]
    },
    {
        id: 4,
        name: 'root2',
        key3: 'value3',
        key4: 'value4',
        children: [
            { id: 5, name: 'child2.1' },
            {
                id: 6,
                name: 'child2.2',
                key5: 'value5',
                key6: 'value6',
                children: [{
                    id: 7,
                    name: 'subsub',
                    children: [{
                        id: 8,
                        name: 'subsubsub'
                    }]
                }]
            }
        ]
    }
];

const getFinalNode = function(arr){
  arr.forEach(function(obj, idx){
    let tmpObj = {
      id: obj.id,
      name: obj.name,
    }
    if(obj.children && obj.children.length){
      tmpObj.children = getFinalNode(obj.children)
    }
    arr[idx] = tmpObj
  })
  return arr
}
getFinalNode(nodes);
console.log(nodes)

Upvotes: 0

Related Questions