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
                   }]
          }]
    }
3
  • Does this answer from another question help? Commented Sep 28, 2017 at 18:33
  • no, because my json object nested element is not known. it can be nested upto 10 stages. and i don't know the stages in advance. Commented Sep 28, 2017 at 18:35
  • Can't you just check for object key existence? Like hasOwnProperty? Commented Sep 28, 2017 at 18:36

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.