Using the Rest Syntax With Object Destructuring
You can simply use the rest syntax with object destructuring to omit some properties from an object and get a new object with the remaining properties, for example, like so:
// ES9+
const obj = { foo: 'bar', baz: 'qux', quux: 'quuz', corge: 'grault' };
const { quux, corge, ...rest } = obj;
console.log(rest); // {foo: 'bar', baz: 'qux'}
You may name the rest params anything other than "rest".
Using Object.assign() With delete
In ES6+, you may use Object.assign() method to copy all (enumerable own properties) of an object and then delete the unwanted properties from the new copy. For example:
// ES6+
const obj = { foo: 'bar', baz: 'qux', quux: 'quuz', corge: 'grault' };
const objCopy = Object.assign({}, obj);
delete objCopy.quux;
delete objCopy.corge;
console.log(objCopy); // {foo: 'bar', baz: 'qux'}
Creating New Object From Entries With Filtered Properties
In ES10+, you may use Object.entries() to iterate over the object's own enumerable string-keyed property [key, value] pairs and filter out the unwanted properties. After that you can simply create a new object from the filtered entries. For example:
// ES10+
const obj = { foo: 'bar', baz: 'qux', quux: 'quuz', corge: 'grault' };
const excludeKeys = new Set([ 'quux', 'corge' ]);
const filteredPairs = Object.entries(obj).filter(([ key ]) => !excludeKeys.has(key));
const newObj = Object.fromEntries(filteredPairs);
console.log(newObj); // {foo: 'bar', baz: 'qux'}
console.log(filteredPairs); // [['foo', 'bar'], ['baz', 'qux']]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.