Get json throught a string

Great script that get an object nested with an string

by Christian Unigarro

JavaScript

var ob = {
    object1: {
        attribute1: 'foo',
        attribute2: 'bar'
    },
    object2: {
        attribute1: 'hello',
        attribute2: 'world'
    }
};

function fetchFromObject(obj, prop){
    //property not found
    if(typeof obj === 'undefined') return false;
    
    //index of next property split
    var _index = prop.indexOf('.')

    //property split found; recursive call
    if(_index > -1){
        //get object at property (before split), pass on remainder
        console.log('este');
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index+1));
    }
    
    //no split; get property
    return obj[prop];
}

console.log(fetchFromObject(ob, 'object2.attribute1'));