首页 > 解决方案 > 如何遍历 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 */
});

对象内的功能是否受到影响?

标签: javascript

解决方案


您可以遍历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);


推荐阅读