Ask any question about JavaScript here... and get an instant response.
Can I use the spread operator to merge two objects while excluding certain properties from one of them?
Asked on Nov 28, 2025
Answer
Yes, you can use the spread operator to merge two objects and exclude certain properties by using destructuring assignment. Here's how you can do it:
<!-- BEGIN COPY / PASTE -->
const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { d: 4, e: 5 };
// Destructure and exclude property 'b'
const { b, ...obj1WithoutB } = obj1;
// Merge the objects
const mergedObj = { ...obj1WithoutB, ...obj2 };
console.log(mergedObj); // Output: { a: 1, c: 3, d: 4, e: 5 }
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The spread operator (...) is used to copy properties from one object to another.
- Destructuring assignment with the syntax "{ b, ...obj1WithoutB }" removes the property "b" from "obj1".
- The final merged object, "mergedObj", includes all properties from "obj1" except "b", and all properties from "obj2".
- This approach is clean and leverages ES6+ features effectively.
Recommended Links:
