rafaelmaeuer
3/13/2018 - 2:24 PM

javascript test for existence of nested object key

// Warning: This solution is not chain-safe
// var level3 = (((test || {}).level1 || {}).level2 || {}).level3;
// alert( level3 );

// ES6 UPDATE
function checkNested(obj, level,  ...rest) {
  if (obj === undefined) return false
  if (rest.length == 0 && obj.hasOwnProperty(level)) return true
  return checkNested(obj[level], ...rest)
}

// ES2020 UPDATE
const value = obj?.level1?.level2?.level3;
obj?.level1?.method();