2

Because null and undefined are not objects in JavaScript, I guess it could be a global helper function?

Example usage could be something like:

var a = { b: { c: { d: 'hello world!' } } };
tryPath(a, 'b', 'c', 'd'); // returns 'hello world!'
tryPath(a, 'x', 'c', 'd'); // returns undefined
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
multipolygon
  • 2,194
  • 2
  • 19
  • 23
  • possible duplicate of [Possible to ignore Cannot read property '0' of undefined?](http://stackoverflow.com/questions/22145087/possible-to-ignore-cannot-read-property-0-of-undefined) – Qantas 94 Heavy Apr 09 '14 at 01:57

3 Answers3

2

You can even shorten it with Array.prototype.reduce, like this

function tryPath(object) {
    var path = Array.prototype.slice.call(arguments, 1);
    if (!path.length) return undefined;
    return path.reduce(function(result, current) {
        return result === undefined ? result : result[current];
    }, object);
}

var a = { b: { c: { d: 'hello world!' } } };
console.assert(tryPath(a, 'b', 'c', 'd') === 'hello world!');
console.assert(tryPath(a, 'x', 'c', 'd') === undefined);
console.assert(tryPath(a) === undefined);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

You can do something fairly simple without a helper function:

var a = { b: { c: { d: 'hello world!' } } };
a && a.b && a.b.c && a.b.c.d; // returns 'hello world!'
a && a.x && a.x.c && a.x.c.d; // returns undefined
David Calhoun
  • 8,315
  • 4
  • 30
  • 23
0
var tryPath = function tryPath() {
    if (arguments.length < 2) {
        return undefined; // Not valid
    } else {
        var object = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            if (object !== null && typeof object === 'object') {
                object = object[arguments[i]];
            } else {
                return undefined;
            }
        }
        return object;
    }
};
multipolygon
  • 2,194
  • 2
  • 19
  • 23