3
var foo = function(o) {...

Parameter o may be null, or it may or may not contain certain nested objects.

I want to find the value of o.foo.bar.baz.chomp.mumble. If any of mumble or its containing objects is null, I want to get null.

I can do this (in this case, I can assume all the path elements are either objects or don't exist -- none are non null, non objects):

var mumble = o && o.foo && o.foo.bar && o.foo.bar.baz 
   && o.foo.bar.baz.chomp ?  o.foo.bar.baz.chomp.mumble : null;

Or I can do this:

var mumble = null;
try { 
   mumble = o.foo.bar.baz.chomp.mumble;
} 
catch { //ignore null pointer exception}

Or I can do this:

var nestedVal = function( o, a ) { 

    if( isString( a ) ) {
        a = a.split( '.' );
    }
    var i = 0, j = a.length;
    for( ; o && isObject( o ) && i < j; ++i) { 
        o = o[ a[ i ] ];
    } 
    return i == j ? o : null;
};


var mumble = nestedValue(o, "foo.bar.baz.chomp.mumble");

Which is preferable, or is there a fourth, better, way to do this?

LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
tpdi
  • 34,554
  • 11
  • 80
  • 120

1 Answers1

1

It depends! The first two solutions fix the property names and that seems over restrictive. I would tend to opt for your last solution as the most flexible. However my implementation would be the following :

var nestedVal = function (o, a) { 
    return a.split ('.').reduce (
      function (o, p) { 
        return o && p in o ? o[p] : null; 
      }, o);
};

In your solution the behavior if a is not a string seems arbitrary. Are you allowing a to be an array of property names ? My solution requires parameter a to be a string.

HBP
  • 15,685
  • 6
  • 28
  • 34