Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate throught javascript properties but skipping the function within it?

Tags:

javascript

I have an object which contains a properties and a methods. I want to iterate throught it and make every single properties within it become null and leave the function as is. The object looks like this:

let Obj = {
   prop1: /* somevalue */
   prop2: /* somevalue */
   /* another properties goes here */
   func1: () => {
      /* do something */
   }
   /* another functions goes here */
}

could I do it with:

Object.keys(filter).forEach((key, index) => {
   /* assign null to properties */
});

Are functions within object getting affected?

like image 589
Raka Pratama Avatar asked Oct 28 '25 08:10

Raka Pratama


1 Answers

You might iterate over the entries and check the typeof each value - if it's not function, assign null to the property:

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);
like image 61
CertainPerformance Avatar answered Oct 30 '25 23:10

CertainPerformance