ChrisRich
ChrisRich

Reputation: 8736

Search object with namespace / key

I'm trying to write a function that can look up a namespace and value in a JavaScript object and return the key.

Image this data:

var o = {

    map: {
        lat : -33.86749,
        lng : 151.20699,
        zoom : 12
    },

    filters : {
        animals : {
            dogs: {
                myDog : 'fido'
            }
        }
    }
};

function get(namespace, key){
    //TODO
}

get('filters.animals.dogs', 'myDog')

How would you build a function that does this dynamically - no matter the depth of the namespace?

This function is somewhat close, only it modifies the original object which we don't want ofcourse:

var get = function(obj, namespace, key, value) {

    var parts = namespace.split('.');

    for(var i = 0; i < parts.length; i++) {
        if(typeof obj[parts[i]] == 'undefined'){
            obj[parts[i]] = {};
        }

        obj = obj[parts[i]];
    }

    return obj[key] = value;
};

Reason for the madness is that I cannot expose the object. It must remain private and a public method must spit out a result.

Upvotes: 3

Views: 616

Answers (2)

abhinsit
abhinsit

Reputation: 3272

I have created a fiddle with working code. Hope that helps.

http://jsfiddle.net/RdhJF/2/

var o = {

    map: {
        lat : -33.86749,
        lng : 151.20699,
        zoom : 12
    },

    filters : {
        animals : {
            dogs: {
                myDog : 'fido'
            }
        }
    }
};




function get(obj, namespace) 
{
    var parts = namespace.split('.');

    if(parts.length==0)
        return -1;


    var previousValue = obj;

    for(var i = 0; i < parts.length; i++) 
    {
        if(typeof previousValue[parts[i]] == 'undefined')
            return -1;
        else
            previousValue = previousValue[parts[i]];

    }

    return previousValue;
}

var myValue= get(o,'filters.animals.dogs.myDog');
alert(myValue);

Upvotes: 0

kalley
kalley

Reputation: 18462

Give this a try.

function get(namespace, key) {
    var parts = namespace.split('.'),
        i = 0,
        l = parts.length,
        obj = o;
    while ( i < l ) {
        obj = obj[parts[i]];
        if ( ! obj ) break;
        i++; 
    }
    return obj && obj[key] ? obj[key] : null;
}

Upvotes: 3

Related Questions