Skip to content Skip to sidebar Skip to footer

Calling Object Properties In N Levels Javascript

I'm using mongodb and ajax calls to retrieve data. When it turns to javascript object, the properties that I use to generate html sometimes don't exist. Look at this call: $.ajax({

Solution 1:

Replace the if statement in the get_property function with the for loop from the checkNested function. Then instead of returning true or false, return the value found or "".

functionget_property(obj){
    var args = Array.prototype.slice.call(arguments),
        obj = args.shift();

     // Here's your 'for' loop. The 'if' statement is gone.for (var i = 0; i < args.length; i++) {
        if (!obj.hasOwnProperty(args[i])) {
          return"";   // I changed the value of this 'return' statement
        }
        obj = obj[args[i]];
    }
    return obj;  // I change the value of this 'return' statement
}

Again, all I did was copy paste your own code from one function to the other, and change the values of the return statements.

Solution 2:

You can achieve your goal by this way (no need of checkNested function):

//Parameters    {obj, prop1, prop2, ... propN}functionget_property(){
    var args = Array.prototype.slice.call(arguments),
       obj = args.shift(),
       prop = args.shift();

    if( obj.hasOwnProperty(prop) ){
        if( args.length > 0 ){
           //Calling 'get_property' with  {obj[prop1], prop2, ... propN} , and so onreturn get_property.apply(get_property, [obj[prop]].concat(args));
        }else{
           return obj[prop];
        }
    }else{
        return"";
    }
}​

Usage:

var o = {
    "a" : {
        "b" : 5
    }
};

console.log( get_property(o,"c") );        //  ""console.log( get_property(o,"a","b") );    //  5console.log( get_property(o,"a") );        //  {"b":5}

Solution 3:

You're just looking for a simple recursive function.

function get_property(obj, prop) {
    if (obj[prop]) {
        return obj[prop];
    }
    else {
        var end;
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                end = get_property(obj[p], prop);
            }
        }
        if (!end) {
            // If we're there, it means there's no property in any nested levelreturn;
        }
        else {
            return end;
        }
    }
}

Edit: looks like I misinterpreted your question. See @Engineer's answer instead. Keeping this answer in case someone looks like for something like this.

Solution 4:

You're overcomplicating things. If you know the tree of your object, just call:

obj['user']['name'];

If you're expecting undefined properties (and really, that means there's something else wrong):

var prop;
try {
    prop = obj.user.name;
}
catch (e) {
    prop = null;
}

Post a Comment for "Calling Object Properties In N Levels Javascript"