1

I got this string of code, data is value returned inside a success callback in an ajax environment:

$('#cpt_rspp_value').text(data.Payload.Clerks.rspp.full_name)
$('#cpt_ddl_value').text(data.Payload.Clerks.ddl.full_name)
$('#cpt_rls_value').text(data.Payload.Clerks.rls.full_name)
$('#cpt_mc_value').text(data.Payload.Cler.mc.full_name)
$('#cpt_se_value').text(data.Payload.Clerks.se.full_name)

If, rspp really exists inside the DB the object data.Payload.Clerks.rspp.full_name will be present, so I can put it in right place (i.e: #cpt_rspp_value). But, alas, if that object doesn't exist, the js interpreter will stop, and so, even if next objects data.Payload.Clerks.ddl.full_name, data.Payload.Clerks.rls.full_name and so on, will be present, that row will never been processed.

I should "if" any lines, but how? if(data.Payload.Clerks.rspp.full_name) and if(data.Payload.Clerks.rspp.full_name != null) don't resolve the issue. What can I do?

2 Answers 2

6

You can use typeof javascript operator to check if the object defined,

if(typeof data.Payload.Clerks.rspp.full_name != 'undefined')

or

if(typeof data.Payload.Clerks.rspp != 'undefined')
1
  • In my case, the right code is if(typeof data.Payload.Clerks.rspp != 'undefined') without full_name, cause rspp is missing too.
    – BAD_SEED
    Commented Sep 8, 2012 at 8:46
3

For checking if it's strictly an object

if(typeof myobject === 'object')

In your case, check for string type

if( typeof data.Payload.Clerks.rspp.full_name === 'string')

Personal opinion - you could just use if(rspp.full_name) since it's a trivial check in the larger scheme of things. (from what it seems like in the question) :)

Not the answer you're looking for? Browse other questions tagged or ask your own question.