如何迭代javascript属性但跳过其中的函数?

问题描述 投票:3回答:4

我有一个包含属性和方法的对象。我想迭代它并使其中的每个属性变为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
4个回答
1
投票

您可以迭代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);

1
投票

您可以使用for...in循环键并将非函数属性设置为null

let filter = {
  prop1: "1",
  prop2: "2",
  func1: () => { }
}

for (let key in filter) {
  if (typeof filter[key] !== "function")
    filter[key] = null
}

console.log(filter)

或者,你可以得到Object.keys创建的对象的JSON.parse(JSON.stringify(filter))

JSON.stringify()创建一个没有function属性的JSON字符串。然后使用JSON.parse()将其转换回对象

let filter = {prop1:"1",prop2:"2",func1:()=>{}}

Object.keys(JSON.parse(JSON.stringify(filter))).forEach((key, index) => {
  console.log(key)
});

0
投票

您可以使用typeof测试它是否是一个函数 - 如果是,则不要做任何事情。如果不是,那么分配它null

let Obj = {
   prop1: 'prop1',
   prop2: 'prop2',
   func1: () => {}
}
Object.keys(Obj).forEach(key => {
    Obj[key] = typeof Obj[key] == "function" ? Obj[key] : null;
});
console.log(Obj);

0
投票
filter(e=>typeof e!=='function')

在过滤器中删除具有类型函数的值。

let Obj = {
  prop1: 'a',
  /* somevalue */
  prop2: 'b',
  /* somevalue */
  /* another properties goes here */
  func1: () => {
    /* do something */
    return 'ab'
  }
  /* another functions goes here */
}

Object.keys(Obj).filter(e => typeof Obj[e] !== 'function').forEach(x => Obj[x] = null)
console.log(Obj)
© www.soinside.com 2019 - 2024. All rights reserved.