How to Ignore a Field When Destructuring an Object in JavaScript
Suppose we want to perform some object destructuring, but we want to ignore, or omit, certain variables from the object.
Read about object destructuring in TypeScript.
Example scenario
Suppose we have a testObject
with an a
, b
, and c
field.
const testObject = {
a: 0,
b: 0,
c: 0
}
We want to destructure this object, but ignore the b
field.
Using spread operator and delete
We can use the delete
keyword to remove
const shallowCopy = { ...testObject };
delete shallowCopy.b;
Now, testObject
will still contain a
, b
, and c
, but shallowCopy
will be missing b
.
Using Object.assign()
and delete
We can also create a shallow copy of the object using Object.assign()
.
let shallowCopy = Object.assign({}, testObject);
delete shallowCopy.b;
Unless we know for sure that the object will contain the property we want to delete or if there are too many properties to list, it is preferable to explicitly list out the destructured properties.