0

I need to do something with an object. Unfortunately the system I'm doing this with (Titanium) expects values to be non-null, otherwise it will segfault. The input, however, cannot be guaranteed to provide sane objects. Here is an example:

var data = {
  foo: {
    bar: "foobar"
  }
};
function do_it(data) {
  do_something_with_non_null_value(data.foo.bar);
}

However it is entirely possible that data is any of the following:

var data = null;
var data = {
  foo: null
};
var data = {
  foo: {
    bar: null
  }
};

How can I test for a non-null value in a deep but concise manor to prevent the do_something_with_non_null_value() from crashing?

Underscore.js answers are also welcome.

Sukima
  • 9,965
  • 3
  • 46
  • 60
  • http://stackoverflow.com/questions/4676223/check-if-object-member-exists-in-nested-object – goat Jul 01 '13 at 13:28

1 Answers1

1

How about using defaults method from underscore?

function do_it(data) {

  var defaults = {
    foo: {
      bar: null
    }
  };

  data = _.defaults(data || {}, defaults);

  do_something_with_non_null_value(data.foo.bar);
}

If data is any of this:

var data = null;
var data = {
  foo: null
};

Will change the object to:

var data = {
  foo: {
    bar: null
  }
};
Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
  • Well this won't help the case when data is more then 3 levels deep. It does fit the bill in regards to the question. Well done. – Sukima Jul 01 '13 at 13:38