Lodash isUndefined提供了意想不到的结果

Lodash isUndefined providing unexpected result

本文关键字:意想不到 结果 isUndefined Lodash      更新时间:2023-09-26

我在Node中使用Lodash是未定义的:sendUser.company = _.isUndefined(user.accounts[0].name) ? null : user.accounts[0].name;但当我试着运行它时,我得到TypeError: Cannot read property 'name' of undefined。不知道我在这里错过了什么

似乎帐户[0]也可能是未定义的-因此您也需要检查这一点:

sendUser.company = ! user.accounts[0] || _.isUndefined(user.accounts[0].name) ? null : user.accounts[0].name;

您确定该用户。Accounts[0]实际上是定义的吗?

这看起来像你正在尝试检查'name'是否未定义。从我对_isUndefined()的理解来看,它只会查找特定的值,因此不能检查作为用户的.name属性的状态。Accounts[0]本身未定义。

你也可以在检查。name属性之前检查它

您可以使用_。get使其安全:

sendUser.company = _.get(user, 'accounts[0].name') || null;