881

If I have a reference to an object:

var test = {};

that will potentially (but not immediately) have nested objects, something like:

{level1: {level2: {level3: "level3"}}};

What is the best way to check for the existence of property in deeply nested objects?

alert(test.level1); yields undefined, but alert(test.level1.level2.level3); fails.

I’m currently doing something like this:

if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
    alert(test.level1.level2.level3);
}

but I was wondering if there’s a better way.

9
  • 1
    you might want to check a tangentially related question that was asked recently stackoverflow.com/questions/2525943/… Commented Apr 13, 2010 at 16:21
  • See also stackoverflow.com/questions/10918488/… Commented Dec 21, 2012 at 15:38
  • A couple of propositions there : stackoverflow.com/a/18381564/1636522 Commented Sep 7, 2013 at 7:27
  • Your current approach has a potential issue if level3 property is a false, in that case, even if the property exist will retur nfalse have a look at this example please jsfiddle.net/maz9bLjx Commented Jul 11, 2015 at 6:18
  • 13
    simply you can use try catch also Commented Aug 12, 2015 at 12:07

64 Answers 64

2

theres a function here on thecodeabode (safeRead) which will do this in a safe manner... i.e.

safeRead(test, 'level1', 'level2', 'level3');

if any property is null or undefined, an empty string is returned

Sign up to request clarification or add additional context in comments.

1 Comment

I kind of like this method with templating because it returns an empty string if not set
2

I wrote my own function that takes the desired path, and has a good and bad callback function.

function checkForPathInObject(object, path, callbackGood, callbackBad){
    var pathParts = path.split(".");
    var currentObjectPath = object;

    // Test every step to see if it exists in object
    for(var i=0; i<(pathParts.length); i++){
        var currentPathPart = pathParts[i];
        if(!currentObjectPath.hasOwnProperty(pathParts[i])){
            if(callbackBad){
                callbackBad();
            }
            return false;
        } else {
            currentObjectPath = currentObjectPath[pathParts[i]];
        }
    }

    // call full path in callback
    callbackGood();
}

Usage:

var testObject = {
    level1:{
        level2:{
            level3:{
            }
        }
    }
};


checkForPathInObject(testObject, "level1.level2.level3", function(){alert("good!")}, function(){alert("bad!")}); // good

checkForPathInObject(testObject, "level1.level2.level3.levelNotThere", function(){alert("good!")}, function(){alert("bad!")}); //bad

1 Comment

I though fair to give you credit for the inspiration to adapt your code to my answer
2
//Just in case is not supported or not included by your framework
//***************************************************
Array.prototype.some = function(fn, thisObj) {
  var scope = thisObj || window;
  for ( var i=0, j=this.length; i < j; ++i ) {
    if ( fn.call(scope, this[i], i, this) ) {
      return true;
    }
  }
  return false;
};
//****************************************************

function isSet (object, string) {
  if (!object) return false;
  var childs = string.split('.');
  if (childs.length > 0 ) {
    return !childs.some(function (item) {
      if (item in object) {
        object = object[item]; 
        return false;
      } else return true;
    });
  } else if (string in object) { 
    return true;
  } else return false;
}

var object = {
  data: {
    item: {
      sub_item: {
        bla: {
          here : {
            iam: true
          }
        }
      }
    }
  }
};

console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'x')); // false
console.log(isSet(object,'data.sub_item')); // false
console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'data.item.sub_item.bla.here.iam')); // true

Comments

2

I was having the same issue and and wanted to see if I could come up with a my own solution. This accepts the path you want to check as a string.

function checkPathForTruthy(obj, path) {
  if (/\[[a-zA-Z_]/.test(path)) {
    console.log("Cannot resolve variables in property accessors");
    return false;
  }

  path = path.replace(/\[/g, ".");
  path = path.replace(/]|'|"/g, "");
  path = path.split(".");

  var steps = 0;
  var lastRef = obj;
  var exists = path.every(key => {
    var currentItem = lastRef[path[steps]];
    if (currentItem) {
      lastRef = currentItem;
      steps++;
      return true;
    } else {
      return false;
    }
  });

  return exists;
}

Here is a snippet with some logging and test cases:

console.clear();
var testCases = [
  ["data.Messages[0].Code", true],
  ["data.Messages[1].Code", true],
  ["data.Messages[0]['Code']", true],
  ['data.Messages[0]["Code"]', true],
  ["data[Messages][0]['Code']", false],
  ["data['Messages'][0]['Code']", true]
];
var path = "data.Messages[0].Code";
var obj = {
  data: {
    Messages: [{
      Code: "0"
    }, {
      Code: "1"
    }]
  }
}

function checkPathForTruthy(obj, path) {
  if (/\[[a-zA-Z_]/.test(path)) {
    console.log("Cannot resolve variables in property accessors");
    return false;
  }

  path = path.replace(/\[/g, ".");
  path = path.replace(/]|'|"/g, "");
  path = path.split(".");

  var steps = 0;
  var lastRef = obj;
  var logOutput = [];
  var exists = path.every(key => {
    var currentItem = lastRef[path[steps]];
    if (currentItem) {
      logOutput.push(currentItem);
      lastRef = currentItem;
      steps++;
      return true;
    } else {
      return false;
    }
  });
  console.log(exists, logOutput);
  return exists;
}

testCases.forEach(testCase => {
  if (checkPathForTruthy(obj, testCase[0]) === testCase[1]) {
    console.log("Passed: " + testCase[0]);
  } else {
    console.log("Failed: " + testCase[0] + " expected " + testCase[1]);
  }
});

Comments

2
function getValue(base, strValue) {

    if(base == null) return;
    
    let currentKey = base;
    
    const keys = strValue.split(".");
    
    let parts;
    
    for(let i=1; i < keys.length; i++) {
        parts = keys[i].split("[");
        if(parts == null || parts[0] == null) return;
        let idx;
        if(parts.length > 1) { // if array
            idx = parseInt(parts[1].split("]")[0]);
            currentKey = currentKey[parts[0]][idx];
        } else {
            currentKey = currentKey[parts[0]];
        }
        if(currentKey == null) return;
    }
    return currentKey;
}

Calling the function returns either undefined, if result fails anywhere withing nesting or the value itself

const a = {
  b: {
    c: [
      {
        d: 25
      }
    ]
  }
}
console.log(getValue(a, 'a.b.c[1].d'))
// output
25

Comments

1

Based on a previous comment, here is another version where the main object could not be defined either:

// Supposing that our property is at first.second.third.property:
var property = (((typeof first !== 'undefined' ? first : {}).second || {}).third || {}).property;

Comments

1

Slight edit to this answer to allow nested arrays in the path

var has = function (obj, key) {
    return key.split(".").every(function (x) {
        if (typeof obj != "object" || obj === null || !x in obj)
            return false;
        if (obj.constructor === Array) 
            obj = obj[0];
        obj = obj[x];
        return true;
    });
}

Check linked answer for usages :)

Comments

1

I thought I'd add another one that I came up with today. The reason I am proud of this solution is that it avoids nested brackets that are used in many solutions such as Object Wrap (by Oliver Steele):

(in this example I use an underscore as a placeholder variable, but any variable name will work)

//the 'test' object
var test = {level1: {level2: {level3: 'level3'}}};

let _ = test;

if ((_=_.level1) && (_=_.level2) && (_=_.level3)) {

  let level3 = _;
  //do stuff with level3

}

//you could also use 'stacked' if statements. This helps if your object goes very deep. 
//(formatted without nesting or curly braces except the last one)

let _ = test;

if (_=_.level1)
if (_=_.level2)
if (_=_.level3) {

   let level3 = _;
   //do stuff with level3
}


//or you can indent:
if (_=_.level1)
  if (_=_.level2)
    if (_=_.level3) {

      let level3 = _;
      //do stuff with level3
}

Comments

1

Well there are no really good answer for one-liners to use in html templates, so i made one using ES6 Proxies. You just pass an object or value to the "traverse" function and do as much nested calls as you want closing them with function call which will return value or fallback value. Using:

const testObject = { 
  deep: { 
    nested: { 
      obj: { 
        closure: () => { return "closure" },
        number: 9,
        boolean: true,
        array: [1, 2, { foo: { bar: true } }]
      } 
    }
  }
}

traverse(testObject).deep() 
// {nested: {…}}

traverse(testObject).non.existent() 
// undefined

traverse(testObject).deep.nested.obj.closure()() 
// closure

traverse(testObject).deep.nested.obj.array[5]('fallback')
// fallback

traverse(testObject).deep.nested.obj.array[2]()
// {foo: {…}}

traverse(testObject).deep.nested.obj.array[2].foo.bar()
// true

traverse(testObject).deep.nested.obj.array[2].foo.bar[4]('fallback')
// fallback

traverse(testObject).completely.wrong[3].call().WILL_THROW()
// Uncaught TypeError: Cannot read property 'WILL_THROW' of undefined

Function itself:

const traverse = (input) => {
    // unique empty object
    const unset = new Object();
    // we need wrapper to ensure we have access to the same unique empty object
    const closure = (input) => {
        // wrap each input into this
        const handler = new Function();
        handler.input = input;    
        // return wrappers proxy 
        return new Proxy(handler, {
            // keep traversing
            get: (target, name) => {
                // if undefined supplied as initial input
                if (!target.input) {
                    return closure(unset);
                }
                // otherwise
                if (target.input[name] !== undefined) {
                    // input has that property
                    return closure(target.input[name]);
                } else {
                    return closure(unset);
                }
            },
            // result with fallback
            apply: (target, context, args) => {
                return handler.input === unset ? 
                    args[0] : handler.input;
            }
        })
    }
    return closure(input);    
}

Comments

0

Another ES5 solution:

function hasProperties(object, properties) {
    return !properties.some(function(property){
        if (!object.hasOwnProperty(property)) {
            return true;
        }
        object = object[property];
        return false;
    });
}

Comments

0

My solution that I use since long time (using string unfortunaly, couldn't find better)

function get_if_exist(str){
    try{return eval(str)}
    catch(e){return undefined}
}

// way to use
if(get_if_exist('test.level1.level2.level3')) {
    alert(test.level1.level2.level3);
}

// or simply 
alert(get_if_exist('test.level1.level2.level3'));

edit: this work only if object "test" have global scope/range. else you have to do something like :

// i think it's the most beautiful code I have ever write :p
function get_if_exist(obj){
    return arguments.length==1 || (obj[arguments[1]] && get_if_exist.apply(this,[obj[arguments[1]]].concat([].slice.call(arguments,2))));
}

alert(get_if_exist(test,'level1','level2','level3'));

edit final version to allow 2 method of call :

function get_if_exist(obj){
    var a=arguments, b=a.callee; // replace a.callee by the function name you choose because callee is depreceate, in this case : get_if_exist
    // version 1 calling the version 2
    if(a[1] && ~a[1].indexOf('.')) 
        return b.apply(this,[obj].concat(a[1].split('.')));
    // version 2
    return a.length==1 ? a[0] : (obj[a[1]] && b.apply(this,[obj[a[1]]].concat([].slice.call(a,2))));
}

// method 1
get_if_exist(test,'level1.level2.level3');


// method 2
get_if_exist(test,'level1','level2','level3');

Comments

0

Another option (close to this answer) :

function resolve(root, path){
    try {
        return (new Function(
            'root', 'return root.' + path + ';'
        ))(root);
    } catch (e) {}
}

var tree = { level1: [{ key: 'value' }] };
resolve(tree, 'level1[0].key'); // "value"
resolve(tree, 'level1[1].key'); // undefined

More on this : https://stackoverflow.com/a/18381564/1636522

Comments

0

Yet another version:

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

nestedPropertyExists({a:{b:{c:1}}}, ['a','b','c']); // returns true
nestedPropertyExists({a:{b:{c:1}}}, ['a','b','c','d']); // returns false

Comments

0

I wrote a library called l33teral to help test for nested properties. You can use it like this:

var myObj = {/*...*/};
var hasNestedProperties = leet(myObj).probe('prop1.prop2.prop3');

I do like the ES5/6 solutions here, too.

Comments

0
function isIn(string, object){
    var arr = string.split(".");
    var notFound = true;
    var length = arr.length;
    for (var i = 0; i < length; i++){
        var key = arr[i];
        if (!object.hasOwnProperty(key)){
            notFound = false;
            break;
        }
        if ((i + length) <= length){
            object = object[key];
        }
    }
    return notFound;
}
var musicCollection = {
    hasslehoff: {
        greatestHits : true
    }
};
console.log(isIn("hasslehoff.greatestHits", musicCollection));
console.log(isIn("hasslehoff.worseHits", musicCollection));

here my String based delimiter version.

Comments

0

Based on @Stephane LaFlèche's answer, I came up with my alternative version of the script.

Demo on JSFiddle

var obj = {"a":{"b":{"c":"Hello World"}},"resTest":"potato","success":"This path exists"};
checkForPathInObject = function(object,path,value) {
        var pathParts   = path.split("."),
            result      = false;
        // Check if required parameters are set; if not, return false
        if(!object || typeof object == 'undefined' || !path || typeof path != 'string')
            return false;
        /* Loop through object keys to find a way to the path or check for value
         * If the property does not exist, set result to false
         * If the property is an object, update @object
         * Otherwise, update result */
        for(var i=0;i<pathParts.length;i++){
            var currentPathPart = pathParts[i];
            if(!object.hasOwnProperty( currentPathPart )) {
                result = false;
            } else if (object[ currentPathPart ] && path == pathParts[i]) {
                result = pathParts[i];
                break;
            } else if(typeof object[ currentPathPart ] == 'object') {
                object = object[ currentPathPart ];
            } else {
                result = object[ currentPathPart ];
            }
        }
        /* */
        if(typeof value != 'undefined' && value == result)
            return true;
        return result;
};
// Uncomment the lines below to test the script
// alert( checkForPathInObject(obj,'a.b.c') ); // Results "Hello World"
// alert( checkForPathInObject(obj,'a.success') ); // Returns false
// alert( checkForPathInObject(obj,'resTest', 'potato') ); // Returns true

Comments

0

I am using a function in the following fashion.

var a = {};
a.b = {};
a.b.c = {};
a.b.c.d = "abcdabcd";

function isDefined(objectChainString) {
    try {
        var properties = objectChainString.split('.');
        var currentLevel = properties[0];
        if (currentLevel in window) {
            var consolidatedLevel = window[currentLevel];
            for (var i in properties) {
                if (i == 0) {
                    continue;
                } else {
                    consolidatedLevel = consolidatedLevel[properties[i]];
                }
            }
            if (typeof consolidatedLevel != 'undefined') {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}

// defined
console.log(checkUndefined("a.b.x.d"));
//undefined
console.log(checkUndefined("a.b.c.x"));
console.log(checkUndefined("a.b.x.d"));
console.log(checkUndefined("x.b.c.d"));

2 Comments

wouldn't be better just a try catch?
I guess you can. for example: try { var d = {}; d.e = []; typeof d.e.r.t } catch(err) { console.log(err.message); }
0

The very best and simplest answer is:

var isDefinedPath = function (path) {

    var items = path.split ('.');

    if (!items || items.length < 1 || !(items[0] in window)) { return false; }

    var buffer = [items[0]];
    for (var i = 1, e = items.length; i < e; i ++) {
        buffer.push (items[i]);
        if (eval ('typeof(' + buffer.join ('.') + ') == "undefined"')) {
            return false;
        }
    }

    return true;

}

test: isDefinedPath ('level1.level2.level3');

first level cannot be array, others can

Comments

0

CMS solution works great but usage/syntax can be more convenient. I suggest following

var checkNested = function(obj, structure) {

  var args = structure.split(".");

  for (var i = 0; i < args.length; i++) {
    if (!obj || !obj.hasOwnProperty(args[i])) {
      return false;
    }
    obj = obj[args[i]];
  }
  return true;
};

You can simply use object notation using dot instead of supplying multiple arguments

var test = {level1:{level2:{level3:'level3'}} };

checkNested(test, 'level1.level2.level3'); // true
checkNested(test, 'level1.level2.foo'); // false

Comments

0

Another way to work this out is for example, having the following object :

var x = {
    a: {
        b: 3
    }
};

then, what I did was add the following function to this object :

x.getKey = function(k){
        var r ;
        try {
            r = eval('typeof this.'+k+' !== "undefined"');
        }catch(e){
            r = false;
        }
        if(r !== false){
            return eval('this.'+k);
        }else{
            console.error('Missing key: \''+k+'\'');
            return '';
        }
    };

then you can test :

x.getKey('a.b');

If it's undefined the function returns "" (empty string) else it returns the existing value.

Please also consider this other more complex solution checking the link : JS object has property deep check

Object.prototype.hasOwnNestedProperty = function(propertyPath){
    if(!propertyPath)
        return false;

    var properties = propertyPath.split('.');
    var obj = this;

    for (var i = 0; i < properties.length; i++) {
        var prop = properties[i];

        if(!obj || !obj.hasOwnProperty(prop)){
            return false;
        } else {
            obj = obj[prop];
        }
    }

    return true;
};

// Usage: 
var obj = {
   innerObject:{
       deepObject:{
           value:'Here am I'
       }
   }
}

obj.hasOwnNestedProperty('innerObject.deepObject.value');

P.S.: There is also a recursive version.

Comments

0

you can path object and path seprated with "."

function checkPathExist(obj, path) {
  var pathArray =path.split(".")
  for (var i of pathArray) {
    if (Reflect.get(obj, i)) {
      obj = obj[i];
		
    }else{
		return false;
    }
  }
	return true;
}

var test = {level1:{level2:{level3:'level3'}} };

console.log('level1.level2.level3 => ',checkPathExist(test, 'level1.level2.level3')); // true
console.log( 'level1.level2.foo => ',checkPathExist(test, 'level1.level2.foo')); // false

Comments

0

Here's a little helper function I use that, to me, is pretty simple and straightforward. Hopefully it's helpful to some :).

static issetFromIndices(param, indices, throwException = false) {
    var temp = param;

    try {
        if (!param) {
            throw "Parameter is null.";
        }

        if(!Array.isArray(indices)) {
            throw "Indices parameter must be an array.";
        }

        for (var i = 0; i < indices.length; i++) {
            var index = indices[i];
            if (typeof temp[index] === "undefined") {
                throw "'" + index + "' index is undefined.";
            }


            temp = temp[index];
        }
    } catch (e) {
        if (throwException) {
            throw new Error(e);
        } else {
            return false;
        }
    }

    return temp;
}

var person = {
    hobbies: {
        guitar: {
            type: "electric"
        }
    }
};

var indices = ["hobbies", "guitar", "type"];
var throwException = true;

try {
    var hobbyGuitarType = issetFromIndices(person, indices, throwException);
    console.log("Yay, found index: " + hobbyGuitarType);
} catch(e) {
    console.log(e);
}

1 Comment

It will be more useful if you could add some detail about your answer, like how this code is going to fix the problem and what it does?
0
getValue (o, key1, key2, key3, key4, key5) {
    try {
      return o[key1][key2][key3][key4][key5]
    } catch (e) {
      return null
    }
}

Comments

0

There's a little pattern for this, but can get overwhelming at some times. I suggest you use it for two or three nested at a time.

if (!(foo.bar || {}).weep) return;
// Return if there isn't a 'foo.bar' or 'foo.bar.weep'.

As I maybe forgot to mention, you could also extend this further. Below example shows a check for nested foo.bar.weep.woop or it would return if none are available.

if (!((foo.bar || {}).weep || {}).woop) return;
// So, return if there isn't a 'foo.bar', 'foo.bar.weep', or 'foo.bar.weep.woop'.
// More than this would be overwhelming.

Comments

0

If you happen to be using AngularJs you can use the $parse service to check if a deep object property exists, like this:

if( $parse('model.data.items')(vm) ) {
    vm.model.data.items.push('whatever');
}

to avoid statements like this:

if(vm.model && vm.model.data && vm.model.data.items) {
    ....
}

don't forget to inject the $parse service into your controller

for more info: https://glebbahmutov.com/blog/angularjs-parse-hacks/

Comments

0

Quite a lot of answers but still: why not simpler?

An es5 version of getting the value would be:

function value(obj, keys) {
    if (obj === undefined) return obj;
    if (keys.length === 1 && obj.hasOwnProperty(keys[0])) return obj[keys[0]];
    return value(obj[keys.shift()], keys);
}

if (value(test, ['level1', 'level2', 'level3'])) {
  // do something
}

you could also use it with value(config, ['applet', i, 'height']) || 42

Credits to CMS for his ES6 solution that gave me this idea.

Comments

0
function propsExists(arg) {
  try {
    const result = arg()
  
    if (typeof result !== 'undefined') {
      return true
    }

    return false
  } catch (e) {
    return false;
  }
}

This function will also test for 0, null. If they are present it will also return true.

Example:

function propsExists(arg) {
  try {
    const result = arg()
  
    if (typeof result !== 'undefined') {
      return true
    }

    return false
  } catch (e) {
    return false;
  }
}

let obj = {
  test: {
    a: null,
    b: 0,
    c: undefined,
    d: 4,
    e: 'Hey',
    f: () => {},
    g: 5.4,
    h: false,
    i: true,
    j: {},
    k: [],
    l: {
        a: 1,
    }
  }
};


console.log('obj.test.a', propsExists(() => obj.test.a))
console.log('obj.test.b', propsExists(() => obj.test.b))
console.log('obj.test.c', propsExists(() => obj.test.c))
console.log('obj.test.d', propsExists(() => obj.test.d))
console.log('obj.test.e', propsExists(() => obj.test.e))
console.log('obj.test.f', propsExists(() => obj.test.f))
console.log('obj.test.g', propsExists(() => obj.test.g))
console.log('obj.test.h', propsExists(() => obj.test.h))
console.log('obj.test.i', propsExists(() => obj.test.i))
console.log('obj.test.j', propsExists(() => obj.test.j))
console.log('obj.test.k', propsExists(() => obj.test.k))
console.log('obj.test.l', propsExists(() => obj.test.l))

Comments

0

Another way :

/**
 * This API will return particular object value from JSON Object hierarchy.
 *
 * @param jsonData : json type : JSON data from which we want to get particular object
 * @param objHierarchy : string type : Hierarchical representation of object we want to get,
 *                       For example, 'jsonData.Envelope.Body["return"].patient' OR 'jsonData.Envelope.return.patient'
 *                       Minimal Requirements : 'X.Y' required.
 * @returns evaluated value of objHierarchy from jsonData passed.
 */
function evalJSONData(jsonData, objHierarchy){
    
    if(!jsonData || !objHierarchy){
        return null;
    }
    
    if(objHierarchy.indexOf('["return"]') !== -1){
        objHierarchy = objHierarchy.replace('["return"]','.return');
    }
    
    let objArray = objHierarchy.split(".");
    if(objArray.length === 2){
        return jsonData[objArray[1]];
    }
    return evalJSONData(jsonData[objArray[1]], objHierarchy.substring(objHierarchy.indexOf(".")+1));
}

Comments

0

Simply use https://www.npmjs.com/package/js-aid package for checking for the nested object.

Comments

0

How about this function? Instead of needing to list each nested property separately, it maintains the 'dot' syntax (albeit in a string) making it more readable. It returns undefined or the specified default value if the property isn't found, or the value of the property if found.

val(obj, element, default_value)
    // Recursively checks whether a property of an object exists. Supports multiple-level nested properties separated with '.' characters.
    // obj = the object to test
    // element = (string or array) the name of the element to test for.  To test for a multi-level nested property, separate properties with '.' characters or pass as array)
    // default_value = optional default value to return if the item is not found. Returns undefined if no default_value is specified.
    // Returns the element if it exists, or undefined or optional default_value if not found.
    // Examples: val(obj1, 'prop1.subprop1.subsubprop2');
    // val(obj2, 'p.r.o.p', 'default_value');
    {

        // If no element is being requested, return obj. (ends recursion - exists)
        if (!element || element.length == 0) { return obj; }

        // if the element isn't an object, then it can't have properties. (ends recursion - does not exist)
        if (typeof obj != 'object') { return default_value; }

        // Convert element to array.
        if (typeof element == 'string') { element = element.split('.') };   // Split on dot (.)

        // Recurse into the list of nested properties:
        let first = element.shift();
        return val(obj[first], element, default_value);

    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.