即使属性存在,Node.js hasOwnProperty 也不起作用

cod*_*ess 2 javascript node.js hasownproperty

在我的 Node.js Express 应用程序中,当用户通过护照登录时,用户用户对象将保存在请求中。

它看起来像这样:

{
    "uuid": "caa5cb58-ef92-4de5-a419-ef1478b05dad",
    "first_name": "Sam",
    "last_name": "Smith",
    "email": "sam@email.com",
    "password": "$2a$10$fXYBeoK6s.A8xo2Yfgx4feTLRXpdvaCykZxr7hErKaZDAVeplk.WG",
    "profile_uuid": "db172902-f3c9-456d-8814-53d07d4ea954",
    "isActive": true,
    "deactivate": false,
    "verified": true,
    "ProviderUuid": "7149f8f1-0208-41db-a78e-887e7811a169"
}
Run Code Online (Sandbox Code Playgroud)

但并非每个用户都有 ProviderUuid 密钥。因此,在使用其值之前,我尝试检查 ProviderUuid 键是否存在于用户对象中

var user = req.user;
console.log('---- provider: ' + JSON.stringify(user));
console.log('--- prop: ' + user.hasOwnProperty('ProviderUuid')); //returns false
console.log('---- other method prop check: ' + Object.prototype.hasOwnProperty.call(user, "ProviderUuid")); //returns false
if('ProviderUuid' in user){
    //this returns true
}
Run Code Online (Sandbox Code Playgroud)

这样做user.hasOwnProperty('ProviderUuid')并Object.prototype.hasOwnProperty.call(user, "ProviderUuid"))返回 false,但'ProviderUuid' in user返回 true。

我在这里缺少什么?

Cer*_*nce 7

由于in有效,该属性必须是 的原型对象之一上的继承user属性,而不是其user本身。这是此类行为的一个活生生的例子:

const userProto = { foo: 'bar' };

// Create an empty object named `user` whose internal prototype is `userProto`:
const user = Object.create(userProto);

// False, user itself is an empty object, nothing's been assigned to it:
console.log(
  user.hasOwnProperty('foo')
);

// True, `foo` does exist on the *internal prototype* of the `user` object:
console.log(
  'foo' in user
);

// True, `foo` is a property directly on `userProto`:
console.log(
  userProto.hasOwnProperty('foo')
);
Run Code Online (Sandbox Code Playgroud)

因此,如果您想检查名为 的继承属性是否存在ProviderUuidin请像您正在做的那样使用运算符。