Checking to see if a property exists within an object.


D

Daz

Hi everyone.

I am passing data through JSON objects between the server and client
via Ajax. I would like to know if it's possible to check for the
existence of a property within that object without using try and catch
blocks?

I was hoping that there might be something else that will just return
null if the property doesn't exist. If there's not, then it's not a
problem. I can easily make a function that will check to see if the
object exists, and pass back null if it doesn't. I just wanted to save
on unnecessary code if I could.

Many thanks in advance.

Daz.
 
Ad

Advertisements

M

Martin Honnen

Daz said:
I am passing data through JSON objects between the server and client
via Ajax. I would like to know if it's possible to check for the
existence of a property within that object without using try and catch
blocks?

"propertyName" in object
is one way. Or
typeof object.propertyName != 'undefined'
 
S

scripts.contact

Hi everyone.

I am passing data through JSON objects between the server and client
via Ajax. I would like to know if it's possible to check for the
existence of a property within that object without using try and catch
blocks?


Yes. Use in operator :
Boolean='property' in object

Example:
obj={myprop1:222,myprop2}
if('myprop3' in obj) // < false
alert("Yes, myprop3 exists in object obj")

var Var="myprop2"
if(Var in obj) // < true
alert("Yes, myprop2 exists in object obj")
 
Ad

Advertisements


Top