getIfExists

Traverse a multi-level object and return a value. If the object path does not exist, return the supplied negative value or the default of undefined.

by mrbinky3000

JavaScript

function getIfExists(object, path, negative = undefined) {
  if (object === null || typeof object === 'undefined') return negative;
  
  const bits = path.split('.');
  const length = bits.length;
  let i = 0;
  let ret = object;
  
  while (ret !== null && typeof ret[bits[i]] !== 'undefined') {
  	ret = ret[bits[i]]; 
		i += 1;
  }
  
  return (i && i === length) ? ret : negative;
}

const bob = {
  a: {
    b: {
      c: null,
      d: false,
      e: 'hello',
      f: 100,
      g: () => {},
    }
  }
};

// open your browser's console log

console.log('a.b.c', getIfExists(bob, 'a.b.c', 'poo'));
console.log('a.b.d', getIfExists(bob, 'a.b.d', 'poo'));
console.log('a.b.e', getIfExists(bob, 'a.b.e', 'poo'));
console.log('a.b.f', getIfExists(bob, 'a.b.f', 'poo'));
console.log('a.b.g', getIfExists(bob, 'a.b.g', 'poo'));
console.log('a.b', getIfExists(bob, 'a.b', 'poo'));
console.log('a.q', getIfExists(bob, 'a.q', 'poo'));
console.log('q', getIfExists(bob, 'q', 'poo'));
console.log('undefined', getIfExists(undefined, 'q', 'poo'));
console.log('null', getIfExists(undefined, 'q', 'poo'));