简体   繁体   English

NodeJS 检查 object 属性是否不是 null

[英]NodeJS check if object property is not null

I'm working on nodejs and I want to check if my object property is not null when uses a filter:我正在研究nodejs,我想检查我的 object 属性在使用过滤器时是否不是 null :

propositions = propositions.filter((prop) => {
  return prop.issuer.city.equals(req.user.city._id);
});

prop.issuer may be null some time and I want to avoid this comparison when it's null! prop.issuer可能是 null ,我想在它为空时避免这种比较!

I tried this but it's not worked:我试过了,但没有奏效:

propositions = propositions.filter((prop) => {
  return prop.issuer?.city.equals(req.user.city._id);
});

The?.这?。 syntax you used is next generation JS and not supported by all browsers (not sure if it supported in Node or not, but if it is, probably not supported in all versions of Node).您使用的语法是下一代 JS,并非所有浏览器都支持(不确定它是否在 Node 中支持,但如果支持,可能不是所有版本的 Node 都支持)。

return prop.issuer?.city.equals(req.user.city._id)

You can just use simple if statements to overcome this problem though (that is what happens behind the scenes in NextGen JS tools like Babel).不过,您可以使用简单的 if 语句来克服这个问题(这就是像 Babel 这样的 NextGen JS 工具在幕后发生的事情)。

Below is an example:下面是一个例子:

propositions = propositions.filter(prop => {

          //this if will allow all items with props.issuer to pass through
          //could return false if you want to filter out anything without prop.issuer instead
          //Note null==undefined in JavaScript, don't need to check both
          if(prop.issuer==undefined){return true;}

          //below will only be made if prop.issuer is not null or undefined
          return prop.issuer.city.equals(req.user.city._id)
        })
propositions = propositions.filter(prop => prop.issuer ? prop.issuer.city.equals(req.user.city._id) : false)

I assumed you want to filter out propositions with null issuer , that's why I used false as third operand of ternary operator;我假设您想用null issuer过滤掉命题,这就是为什么我使用false作为三元运算符的第三个操作数; if I was wrong, use true .如果我错了,请使用true

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

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