JavaScript clone and rewrite property from existing object


How to overwrite and compose a existing property in an object with JavaScript

6 Jul, 2022 · 2 min read

In JavaScript, we work a lot with Objects, and you'll have to modify some of the object data from time to time.

Let's take the following object as our example.

const user = {
  username: 'Chris',
  online: false,

This user object is used to keep track of all the users and their status.

But what should we do when we want to set the online status to true, but the original one to remain false?

There are multiple good answers to this question, but I'll show you the easiest way to do this in this article.

Using the spread operator to overwrite an object property

We'll use the spread operator, which you can recognize by the three dots.

Let's say we want the status to be true. We can use the following call.

console.log({ ...user, online: true });

// { username: 'Chris', online: true }

It's a super clean syntax and easy to see which value we are overwriting.

The only thing you must remember while using this method is that the order matters.

If we, for instance, put the property we want to overwrite. First, it won't work. This is because the latter assignments always win.

console.log({ online: true, ...user });

// { online: false, username: 'Chris' }

And that's the easiest way to overwrite an object value using JavaScript's spread operator.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2101 devs and subscribe to my newsletter