Languages

JavaScript - updating object property?

0 points
Asked by:
Frida-Timms
667

How can I update object's property in JavaScript?

I have the following object:

I've tried pushing a new value of theme property to myObject like this but it doesn't work:

1 answer
0 points
Answered by:
Admin Dirask Community
4380

ES6+ solutions

1. You can create new object by using spread syntax (...) to copy all the properties from the original object and change only the one you want.

Note:

This solution creates a copy of the original object.

2. Another solution would be to use Object.assign() method to modify the existing object.

Note:

This solution modifies the original object.

Alternative solution

For older versions of JavaScript, you can use property accesors to update the object's value. In the example below, we use dot property accessor.

Note:

This solution modifies the original object.

 

References

  1. Spread syntax (...) - JavaScript | MDN
  2. Object.assign() - JavaScript | MDN
  3. Property accessors - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join