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.
 
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")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top