How to check if an object exists inside an object

It seems that the following method of checking for the existence of a member of an object is creating an error because the parent object "bar" was not declared before validation, which means that I either have to declare it before validation, or use two 'typeof' expressions, of which there will be extra code:

var foo = {}, newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null ); Error: foo.bar is undefined 

So, how do you check if an element exists inside an undeclared object without an error?

I like javascript, but sometimes ...

+8
source share
6 answers

This can be done simply by using the following code:

 var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal 

The property is null or undefined, it will be evaluated as false, so the above code will only process the first 'false' statement.

+9
source
 var newVal = ('foo' in window && // could be typeof foo !== 'undefined' if you want all scopes 'bar' in foo && 'myVal' in foo.bar) ? foo.bar.myVal : null; 

In fairness, javascript that reads almost like a natural language.

+6
source

The easiest test:

 if (foo && foo.bar) { // play with foo.bar.myVal ... } 
+3
source

You can wrap it in a method:

 function checkGraph(obj, graphPath) { var parts = graphPath.split("."); var root = obj; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (root[part] && root.hasOwnProperty(part)) root = root[part]; else return false; } return true; } 

Where could you name it:

 var foo = {}, newVal = checkGraph(foo, "bar.myVal") ? foo.bar.myVal : null; 
+1
source

As Matthew Abbott gave in his answer, you can write a method to use it later if you do a lot of diving into child properties, where the whole object or somewhere along the chain can be null. Below is my implementation using lodash .

 checkGraph(obj, graphPath) { if (obj) { let root = obj; _.each(graphPath.split('.'), part => { if (root[part]) { root = root[part]; } else { return false; // bad property } }); return true; } return false; // bad object } 

You can call the method as follows:

 if (this.checkGraph(object, 'property.subproperty') { // do thing } 
+1
source

There is another way - use a JS transporter like Babel :

 if (foo?.bar) { // play with foo.bar.myVal ... } 
0
source

Source: https://habr.com/ru/post/891817/


All Articles