【发布时间】:2021-08-10 09:52:38
【问题描述】:
我有一个函数可以遍历对象的密钥并查找敏感密钥,例如电子邮件、密钥、密码、apiKey、secrets、secret 和 userKey。
如果它发现任何有值,它会编辑该值。
但是,它有时会出现以下错误:
"RangeError: Maximum call stack size exceeded"
Whats causing the endless recursion??
const deepObjectRedactor = obj => {
const sensitiveKeys = [
'email',
'key',
'password',
'apiKey',
'secrets',
'secret',
'userKey'
];
Object.keys(obj).forEach(key => {
if (
sensitiveKeys.map(e => e.toLowerCase()).includes(key.toLowerCase()) &&
obj[key]
) {
obj[key] = '**********';
return;
}
if (obj[key] && typeof obj[key] === 'object') {
deepObjectRedactor(obj[key]);
}
});
};
// function invoking the redactor
const customRedactorFormat = info => {
if (info.message && typeof info.message === 'object') {
deepObjectRedactor(info.message);
}
return info;
});
【问题讨论】:
-
表示达到内存限制。
-
不满足递归基本情况。
-
sensitiveKeys.find而不是sensitiveKeys.map可能是问题之一。 -
可能是,对象中某处存在循环。由于您的函数不会跟踪已经 seen 对象,因此您将无限递归。还有你的条件很尴尬,为什么不简单:
sensitiveKeys.includes(key.toLowerCase());?sensitiveKeys是一个常量in 你的函数。如果您希望它们全部小写,请将它们定义为全部小写。而不是一遍又一遍地小写它们。 -
@nishkaush 你能提供你的
object的简化变体吗
标签: javascript object recursion