简体   繁体   中英

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 (ie: #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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM