BAD_SEED
BAD_SEED

Reputation: 5056

Check if an object (not an element) really exists with js/jQuery

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?

Upvotes: 1

Views: 121

Answers (2)

Adil
Adil

Reputation: 148120

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')

Upvotes: 6

Robin Maben
Robin Maben

Reputation: 23054

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) :)

Upvotes: 3

Related Questions