javascript - 如何遍历 javascript 属性但跳过其中的函数?
问题描述
我有一个包含属性和方法的对象。我想遍历它并使其中的每个属性都变为 null 并保持函数不变。该对象如下所示:
let Obj = {
prop1: /* somevalue */
prop2: /* somevalue */
/* another properties goes here */
func1: () => {
/* do something */
}
/* another functions goes here */
}
我可以这样做吗:
Object.keys(filter).forEach((key, index) => {
/* assign null to properties */
});
对象内的功能是否受到影响?
解决方案
您可以遍历entries
并检查typeof
每个值 - 如果不是function
,则分配null
给属性:
let Obj = {
prop1: 'prop1',
prop2: 'prop2',
func1: () => {
/* do something */
}
}
Object.entries(Obj).forEach(([key, val]) => {
if (typeof val !== 'function') {
Obj[key] = null;
}
});
console.log(Obj);
推荐阅读
- mysql - 如何回调结果 Mysql + Nodejs
- bash - 如何在 Mac OS 中使用脚本检测文件是别名还是来源
- json - 使用 Object Mapper 将本地 JSON 文件映射到 Realm 对象
- objective-c - 将 NULL 分配给 NSDate* 是否安全?
- javascript - FromGroup 中输入掩码的验证
- java - 嵌套异常是 java.io.FileNotFoundException:
- javascript - 从反应状态制作下拉菜单
- java - Java JPA 从 oracle 数据库中检索 blob 作为其原始文件类型
- qt - 为什么不同的 qquickframebufferobject 显示相同的 opengl 输出?
- python - 在另一个列表中添加列表值的出现