Ask any question about JavaScript here... and get an instant response.
How can I use the spread operator with an object to merge properties while excluding some keys using destructuring?
Asked on Dec 06, 2025
Answer
To merge properties of objects while excluding specific keys, you can use the spread operator along with destructuring assignment. Here's a concise example demonstrating how to achieve this.
const original = { a: 1, b: 2, c: 3, d: 4 };
const { b, d, ...rest } = original;
const merged = { ...rest, e: 5 };
console.log(merged); // Output: { a: 1, c: 3, e: 5 }Additional Comment:
✅ Answered with JavaScript best practices.- In this example, the original object has properties "a", "b", "c", and "d".
- The destructuring assignment `{ b, d, ...rest }` extracts "b" and "d" and collects the remaining properties into the "rest" object.
- The spread operator `{ ...rest, e: 5 }` is used to merge the remaining properties with a new property "e".
- The final "merged" object contains properties "a", "c", and "e", excluding "b" and "d".
Recommended Links:
