简体   繁体   中英

How to check object null and then property null and then assign value if they are null?

I am trying to check if a variable is null inside an object in single line

 let data = {                        
   friends: userData.social.friends?0: userData.social.friends,
}

in the above line how to check if the userData is null and social is null and then friend is null in a single line? i need to set 0 if friends is not there.

this is in my javascript node js app

is falsy sufficient or do you actually need to compare against null ? you could use this pretty standard notation:

let data = {                        
    friends: userData && userData.social && userData.social.friends || 0
}

As you want to check for null as well as assign the value of friends to your variable, i think it will help you out

 let data = { friends: userData ? (userData.social ? (userData.social.friends ? userData.social.friends : 0) : 0) : 0 } 

I hope this fits your need.

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