简体   繁体   English

如何检查对象为null,然后检查属性为null,然后检查它们是否为null?

[英]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? 在上面的行中,如何在一行中检查userData是否为null以及social是否为null,然后friend是否为null? i need to set 0 if friends is not there. 如果朋友不在那里,我需要设置0。

this is in my javascript node js app 这是在我的javascript节点js应用中

is falsy sufficient or do you actually need to compare against null ? 足够虚假还是您实际上需要与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 当您要检查null并将朋友的值分配给变量时,我认为它将为您提供帮助

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

I hope this fits your need. 我希望这符合您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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