Checking to see if a property exists within an object.

Discussion in 'Javascript' started by Daz, May 4, 2007.

  1. Daz

    Daz Guest

    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

    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, May 4, 2007
    1. Advertisements

  2. "propertyName" in object
    is one way. Or
    typeof object.propertyName != 'undefined'
    Martin Honnen, May 4, 2007
    1. Advertisements

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

    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")
, May 4, 2007
  4. Daz

    Daz Guest

    Wonderful. Thanks a lot Martin.
    Daz, May 4, 2007
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.