JScript JSON Object Check

Posted by George on Stack Overflow See other posts from Stack Overflow or by George
Published on 2010-05-04T15:15:08Z Indexed on 2010/05/04 15:18 UTC
Read the original article Hit count: 280

Filed under:
|
|
|

I'm trying to check if json[0]['DATA']['name'][0]['DATA']['first_0'] exists or not when in some instances json[0]['DATA']['name'] contains nothing.

I can check json[0]['DATA']['name'] using

if (json[0]['DATA']['name'] == '') {
    // DOES NOT EXIST
}

however

if (json[0]['DATA']['name'][0]['DATA']['first_0'] == '' || json[0]['DATA']['name'][0]['DATA']['first_0'] == 'undefined') {
    // DOES NOT EXIST
}

returns json[0]['DATA']['name'][0]['DATA'] is null or not an object. I understand this is because the array 'name' doesn't contain anything in this case, but in other cases first_0 does exist and json[0]['DATA']['name'] does return a value.

Is there a way that I can check json[0]['DATA']['name'][0]['DATA']['first_0'] directly without having to do the following?

if (json[0]['DATA']['name'] == '') {
    if (json[0]['DATA']['name'][0]['DATA']['first_0'] != 'undefined') {
    // OBJECT EXISTS
    }
}

© Stack Overflow or respective owner

Related posts about JSON

Related posts about JavaScript