ChrisGciso ChrisGciso - 5 months ago 23
Javascript Question

Returning the value of deep properties if they exist

I wrote this function to search for and return the value of deep properties in an object and would like to know if there is a way to use recursion or something similar to make the function do the same thing but with less code (and possibly to remove the limit of at most five properties deep that can be tested).

The function will return a deep property value if it exists, otherwise returns undefined.

function getDeep(o, p2, p3, p4, p5) {
if (p5 !== undefined) {
if (o.hasOwnProperty(p2) && o[p2].hasOwnProperty(p3) && o[p2][p3].hasOwnProperty(p4) && o[p2][p3][p4].hasOwnProperty(p5)) {
return o[p2][p3][p4][p5];
}
} else if (p4 !== undefined) {
if (o.hasOwnProperty(p2) && o[p2].hasOwnProperty(p3) && o[p2][p3].hasOwnProperty(p4)) {
return o[p2][p3][p4];
}
} else if (p3 !== undefined) {
if (o.hasOwnProperty(p2) && o[p2].hasOwnProperty(p3)) {
return o[p2][p3];
}
} else if (p2 !== undefined) {
if (o.hasOwnProperty(p2)) {
return o[p2];
}
} else if (o !== undefined) {
return o;
}
}
window.onload = function () {
var obj = {a:{b:{c:1}}};
window.console.log(getDeep(obj, 'a', 'b', 'c')); // returns 1;
window.console.log(getDeep(obj, 'a', 'b', 'd')); // returns undefined;
}

Answer

.reduce is useful for this.

Demo: http://jsfiddle.net/NU4vF/2

function getDeep() {
    return [].reduce.call(arguments, function(obj, prop) {
        return obj && obj[prop];
    });
}
Comments