1

I'm using the ES7 Object Rest Operator to Omit Properties from an object, but I'd like to make it more flexible so that I can dynamically provide the list of properties to exclude.

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

Is there a way to make this more dynamic such that I can call a function and provide an array of properties to exclude instead of the hardcoded approach taken with properties a and b in this example?

Ideally I could have something along these lines -- but this syntax is invalid:

function omitProperties(myObj, fieldsToExclude) {
  const { ...fieldsToExclude, ...noA } = myObj;
  console.log(noA); // => { b: 2, c: 3 }
} 

omitProperties(myObject, [`a`]);

Dave
  • 1,111
  • 8
  • 16

1 Answers1

0

You can consider _.omit.

You can also consider the following:

let omitProperties = (props, exclude) => {
  let result = { ...props };
  for (let propName of exclude) delete result[propName];
  return result;
};

There's quite a bit of discussion about this same issue here.

Gershom Maes
  • 7,358
  • 2
  • 35
  • 55