在我的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"
}
但并非每个用户都有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"))
返回false,但是'ProviderUuid' in user
返回true。
我在这里想念什么?
答案 0 :(得分:4)
由于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')
);
因此,如果要检查是否存在名为ProviderUuid
的继承属性,请像执行操作一样使用in
运算符。
答案 1 :(得分:0)
我测试了代码,所有检查均返回true。
var user = {
"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"
};
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
另存为字符串