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.
You have to do it step by step if you don’t want a
TypeErrorbecause if one of the members isnullorundefined, and you try to access a member, an exception will be thrown.You can either simply
catchthe exception, or make a function to test the existence of multiple levels, something like this:ES6 UPDATE:
Here is a shorter version of the original function, using ES6 features and recursion (it’s also in proper tail call form):
However, if you want to get the value of a nested property and not only check its existence, here is a simple one-line function:
The above function allows you to get the value of nested properties, otherwise will return
undefined.UPDATE 2019-10-17:
The optional chaining proposal reached Stage 3 on the ECMAScript committee process, this will allow you to safely access deeply nested properties, by using the token
?., the new optional chaining operator:If any of the levels accessed is
nullorundefinedthe expression will resolve toundefinedby itself.The proposal also allows you to handle method calls safely:
The above expression will produce
undefinedifobj,obj.level1, orobj.level1.methodarenullorundefined, otherwise it will call the function.You can start playing with this feature with Babel using the optional chaining plugin.Since Babel 7.8.0, ES2020 is supported by default
Check this example on the Babel REPL.
UPDATE: December 2019
The optional chaining proposal finally reached Stage 4 in the December 2019 meeting of the TC39 committee. This means this feature will be part of the ECMAScript 2020 Standard.