0

here is a json object i want to loop through:

{
  node: 'tree',
 text: 'Main Node',
  childs:[
      {
        node: 'tree',
        text: 'First Child',
        childs:[{
                node: 'tree',
                text: 'first child child'
               }....]
      },{
        node: 'tree',
        text: '2nd Child',
        childs:[{
                node: 'tree',
                text: '2nd child child'
               }...]
      }...]
}

here is the first type of json. but the problem is that json is dynamic and the child element vary depend upon different conditions. so i want to loop through the json and add leaf: true to the end of the last nested element. here is what is want:

{
      node: 'tree',
     text: 'Main Node',
      childs:[
          {
            node: 'tree',
            text: 'First Child',
            childs:[{
                    node: 'tree',
                    text: 'first child child',
                    leaf: true // i want to add this node to every last one
                   }]
          },{
            node: 'tree',
            text: '2nd Child',
            childs:[{
                    node: 'tree',
                    text: '2nd child child',
                    leaf: true
                   }]
          }]
    }
Waqar Haider
  • 929
  • 10
  • 33

1 Answers1

1

You can do it with a recursive function:

let objt = {
    node: 'tree',
    text: 'Main Node',
    childs: [
        {
            node: 'tree',
            text: 'First Child',
            childs: [{
                node: 'tree',
                text: 'Main Node'
            }]
        }, {
            node: 'tree',
            text: '2nd Child',
            childs: [{
                node: 'tree',
                text: '2nd child child'
            }]
        }]
};


function setLeaf(objt) {
    if (!objt.childs) {
        objt.leaf = true;
    } else {
        objt.childs.forEach(child => setLeaf(child))
    }
}

setLeaf(objt);