traversing through JSON string to inner levels using recursive function

I have made a jsfiddle which traverses every object,array and value in the JS object like so…

function scan(obj) {
    var k;
    if (obj instanceof Object) {
        for (k in obj){
            if (obj.hasOwnProperty(k)){
                //recursive call to scan property
                scan( obj[k] );  
            }                
        }
    } else {
        //obj is not an instance of Object so obj here is a value
    };

};

I get no recursion error (in Chrome). Can you use this to do what you want?

If you need to test if an object is an array use if (obj instanceof Array)

To test if an object has an “entity” property use if (obj.hasOwnProperty('entity'))

To add (or modify an existing) “entity” property use obj.entity = value or obj['entity'] = value

Leave a Comment