Q . javaScript isset(function) equivalent to PHP.

Dev Singh. asked, Sep 20 ' 2017

In PHP you can do if(isset($array['foo'])) { ... }. 
In JavaScript I searched many things for isset equivalent to PHP.
But I get below things which is very lengthy to check every propery.

var jsonObj = { "foo": "bar", "foo2" : { "foo3" : "bar3", "foo4" : "bar4" }};
Case 1.
if(
	jsonObj.hasOwnProperty('foo2') && 
	jsonObj.foo2.hasOwnProperty('foo3')
	jsonObj.foo2.foo3 == 'bar3'
) {....}

 

Case 2.

if (typeof jsonObj.foo2 !== 'undefined' &&
	typeof jsonObj.foo2.foo3 !== 'undefined' &&
	jsonObj.foo2.foo3 == 'bar3'		
) {....}

Isn't there any easy way to check every propery exist or not?

  • JavaScript
  • json
  • isset

1 Answers

You can do it very easily in one condition (using arrow function) just do like below.

if(() => jsonObj.foo2.foo3 && 
	jsonObj.foo2.foo3 == 'bar3'){ ...... }


//() => jsonObj.foo2.foo3
//above commented code will return true if each property exist or either false.

 

Leave a Ansewer