Json Recursive

Iterate through the Json Recursive

by B L Praveen

JavaScript

var root = {
    leftChild: {
        leftChild: {
            leftChild: null,
            rightChild: null,
            data: 42
        },
        rightChild: {
            leftChild: null,
            rightChild: null,
            data: 5
        }
    },
    rightChild: {
        leftChild: {
            leftChild: null,
            rightChild: null,
            data: 6
        },
        rightChild: {
            leftChild: null,
            rightChild: null,
            data: 7
        }
    }
};
function getLeaf(node) {
    while(node instanceof Object) {
    if (node.leftChild) {
        node = getLeaf(node.leftChild);
    } else if (node.rightChild) {
        node = getLeaf(node.rightChild);
    } else { // node must be a leaf node
        return node;
    }
        console.log(node);
   }
}

alert(getLeaf(root).data);