DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

1 1

Rest properties with object destructuring

If we want clone an object but remove certain properties we can use this fancy trick:

const user = {
  firstName: 'Homer',
  lastName: 'Simpson',
  age: 40,
  city: 'Springfield',
};

const { age, ...userWithoutAge } = user;
Enter fullscreen mode Exit fullscreen mode

Let's see what's inside userWithoutAge:

// userWithoutAge
{ 
  firstName: "Homer",
  lastName: "Simpson",
  city: "Springfield"
}
Enter fullscreen mode Exit fullscreen mode

So we have a clone of the original object, but without the age property. Umm, what? 🤔

This is how it works!

First, let's look at a simpler example without the use of the "rest spreading":

const { age, city } = user;

console.log(age); // 40
console.log(city); // Springfield
Enter fullscreen mode Exit fullscreen mode

Here, we're simply destructuring the object to retrieve the age and city properties as new variables. Cool, so let's see what happens when we look at the original example:

const { age, ...userWithoutAge } = user;
Enter fullscreen mode Exit fullscreen mode

First, we destructure the age property as we just saw, but also we utilize object rest spreading to collect the leftover properties into a variable we can name anything; in this case we call it userWithoutAge. This object we just created on the fly now contains all the original user properties except the age!

Using rest properties for object destructuring assignment is a newer feature added in ECMAScript 2018 and is available in modern browsers.

Links

MDN Article on spread syntax


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay