【发布时间】:2017-06-08 12:31:09
【问题描述】:
这是一个在 JSON 对象返回给客户端之前删除敏感信息的函数。传递给函数的数据可以是 JSON 对象或 JSON 对象数组。为什么这个功能不起作用?
我知道这个问题还有其他解决方案,但这让我很烦。
我已经在这个函数中记录了大量信息,尽管 JavaScript 是异步的,但函数正在按照它们应该的顺序运行 - 递归在最后的 return 语句被命中之前完成。
现在的问题是,即使一切似乎都正常工作,并且 delete 运算符正在返回 true,但当函数最终返回时,被删除的属性仍然存在。
从 MongoDB 获取的示例 data:
[
{
'id': '1',
'name': 'John',
'password': 'test123',
'emailAddress': 'john@example.com',
'emailAddressVerificationCode': 'A897D'
},
{
'id': '2',
'name': 'Andrew',
'password': 'test123',
'emailAddress': 'andrew@example.com',
'emailAddressVerificationCode': '90H8D'
},
{
'id': '3',
'name': 'Matthew',
'password': 'test123',
'emailAddress': 'matthew@example.com',
'emailAddressVerificationCode': '56C7C'
}
]
任何想法将不胜感激。
UserService.cleanJSON = (data) => {
if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++){
data[i] = UserService.cleanJSON(data[i]);
}
} else {
if (data.password) delete data.password;
if (data.emailAddressVerficationCode) delete data.emailAddressVerficationCode;
if (data.mobileNumberVerificationCode) delete data.mobileNumberVerificationCode;
if (data.accountType) delete data.accountType;
}
return data;
};
【问题讨论】:
-
你能提供一个
data的初始化示例吗? -
另外,
probably与您的问题无关,但可能不需要从函数中返回data,因为它正在编辑通过引用传入的原始对象。 -
此功能将按预期工作。问题出在其他地方。
-
这一行是错字吗?
if (data.emailAddressVerficationCode) delete data.emailAddressVerficationCode;验证而不是验证。除此之外,它在 Chrome 控制台中对我来说很好用。 -
当我运行代码时,它会删除
password属性,所以@MezoIstvan 是正确的。
标签: javascript json node.js mongoose ecmascript-6