Removing Properties Immutably
You'll learn how to exclude specific properties from an object while preserving the rest, without modifying the original.
When working immutably with objects, you sometimes need to create a new object that's identical to the original except for certain properties you want to remove. JavaScript doesn't have a built-in "remove property immutably" method, but you can combine destructuring with the rest operator to achieve this elegantly.
The Core Technique
The trick is to destructure the properties you don't want into throwaway variables, then collect everything else using the rest operator (...). The rest variable captures all remaining properties as a new object.
const user = {
id: 101,
name: "Alice",
password: "secret123",
email: "alice@example.com"
};
// Remove 'password' immutably
const { password, ...safeUser } = user;
console.log(safeUser);
// { id: 101, name: "Alice", email: "alice@example.com" }
console.log(user);
// Still has password — original unchanged
Removing Multiple Properties
You can destructure multiple properties to exclude them all:
const product = {
id: 5,
name: "Laptop",
internalCost: 500,
markup: 1.5,
price: 750
};
const { internalCost, markup, ...publicProduct } = product;
console.log(publicProduct);
// { id: 5, name: "Laptop", price: 750 }
Think of It Like Filtering
Imagine you have a deck of cards and want a new deck without the jokers. You pick out the jokers (destructure them), then gather all remaining cards into a fresh pile (rest operator). Your original deck stays intact.
Key Takeaway: Use destructuring with the rest operator (const { unwanted, ...kept } = obj) to exclude specific properties and create a new object immutably—perfect for sensitive data removal or API response sanitization.