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

Node.js hasOwnProperty does not work even when the property exists

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

看起来像这样:

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

但并非每个用户都有 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
}

这样做 user.hasOwnProperty('ProviderUuid') 和 Object.prototype.hasOwnProperty.call(user, "ProviderUuid")) returns 错误,但是 'ProviderUuid' in user returns 正确。

我在这里错过了什么?

由于 in 有效,属性 必须 inherited 属性,在 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')
);

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

我测试了代码,所有检查都返回了 true。

var user = {
    "uuid": "caa5cb58-ef92-4de5-a419-ef1478b05dad",
    "first_name": "Sam",
    "last_name": "Smith",
    "email": "sam@email.com",
    "password": "a$fXYBeoK6s.A8xo2Yfgx4feTLRXpdvaCykZxr7hErKaZDAVeplk.WG",
    "profile_uuid": "db172902-f3c9-456d-8814-53d07d4ea954",
    "isActive": true,
    "deactivate": false,
    "verified": true,
    "ProviderUuid": "7149f8f1-0208-41db-a78e-887e7811a169"
};
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
}

尝试JSON.parse(),也许req.user保存为字符串