Subscribe

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 📖

Using the native payment request JavaScript API

9 Aug, 2022 · 8 min read

Using the native payment request JavaScript API

JavaScript if shorthand without the else

1 Aug, 2022 · 2 min read

JavaScript if shorthand without the else

Join 1748 devs and subscribe to my newsletter