What is the method called to safely check for object properties?

I read an article sometime back, when researching an unrelated bug… It exposed a nice way of combining the if statements to reduce the number of errors when checking for if a property is set…

For example:
if (object) {
if (object.isSet) {
doSomething();
}
}

You’re talking about simple schema or collection2.

Do you mean this, as a more concise way of doing the same thing?

if (object && object.isSet) {
  doSomething();
}

Do you mean the Underscore function for it?

if (_.has(object, "isSet")) {
    doSomething();
}

lookup underscore deep, it would let you specify a property (deep) path within an object and fetch the property safely

Very short line:

_.has(object, “isSet”) && doSomething();

or also

_.has(object, “isSet”) || doError();

For the record, Meteor has an undocumented function (Meteor._get) that does what @chenroth is talking about.

For instance, given an object like this

var person = {
  name : {
    first: {
      full: "John",
      nickname: "Jack"
    },
    second: "Adams"
  }
}

you can write

if (Meteor._get(person, "name", "first", "nickname")) {
  console.log("Person has a nickname.");
}

rather than

if (person && person.name && person.name.first && person.name.first.nickname) {
  console.log("Person has a nickname.");
}

Note: the Meteor._get function will throw an error if person is not an object.

I often use something like this instead

getVal = function (obj, key) {
  obj = _.isObject(obj) && obj || {};
  return Meteor._get.apply(null,[obj].concat(key.split('.')));
}

Then you can do things like

if (getVal(person, "name.first.nickname")) {
  console.log("Person has a nickname.");
}
2 Likes