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`]);