diwiny
8/7/2018 - 3:09 PM

Check existence of nested object key

Check existence of nested object key

let obj = {
  levelOne: {
    levelTwo: {
      levelThree: {
        asd: 'kek'
      }
    }
  }
}

// Source: https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key
// Benchmarked with: http://jsben.ch/7aJgK
// Use whathever you want. 
// Existence checking

// Object Wrap (by Oliver Steele) – 34 % – fastest
var r1 = ((((obj || {}).levelOne || {}).levelTwo || {}).levelThree || {}).asd; // exists returns: kek
var r2 = ((((obj || {}).levelOne || {}).levelTwo || {}).levelThree || {}).notFound; // not exists returns: undefined

// Standard solution – 45%
var r1 = obj.levelOne && obj.levelOne.levelTwo && obj.levelOne.levelTwo.levelThree && obj.levelOne.levelTwo.levelThree.asd // exists returns: kek
var r1 = obj.levelOne && obj.levelOne.levelTwo && obj.levelOne.levelTwo.levelThree && obj.levelOne.levelTwo.levelThree.notFound // not exists returns: undefined

// checkNested – 50%

function checkNested(obj) {
  for (var i = 1; i < arguments.length; i++) {
    if (!obj.hasOwnProperty(arguments[i])) {
      return false;
    }
    obj = obj[arguments[i]];
  }
  return true;
}

// get_if_exist – 52%
function get_if_exist(str) {
    try { return eval(str) }
    catch(e) { return undefined }
}

// validChain – 54%
function validChain( object, ...keys ) {
    return keys.reduce( ( a, b ) => ( a || { } )[ b ], object ) !== undefined;
}

// objHasKeys – 63%
function objHasKeys(obj, keys) {
  var next = keys.shift();
  return obj[next] && (! keys.length || objHasKeys(obj[next], keys));
}

// nestedPropertyExists – 69%
function nestedPropertyExists(obj, props) {
    var prop = props.shift();
    return prop === undefined ? true : obj.hasOwnProperty(prop) ? nestedPropertyExists(obj[prop], props) : false;
}

// Lodash get _.get – 72%

// deeptest – 86%
function deeptest(target, s){
    s= s.split('.')
    var obj= target[s.shift()];
    while(obj && s.length) obj= obj[s.shift()];
    return obj;
}

// sad clowns – 100% – slowest
var o = function(obj) { return obj || {} };

var r1 = o(o(o(o(test).level1).level2).level3);
var r2 = o(o(o(o(test).level1).level2).foo);