Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update an object in object – javascript

I have an object with a lot of properties and with nested objects. I need to update some properties including the ones which are in the nested objects.
What is the best way to do that?

First I tried this way:

  adjustedConfig.stars.size = 20;
  adjustedConfig.width = 1800;
  adjustedConfig.disableAnimations = true;
  adjustedConfig.stars.exponent = -0.26;
  adjustedConfig.stars.limit = 10;
  adjustedConfig.constellations.lineStyle.width = 2;
  adjustedConfig.background.width = 4; 

this approach has 2 problems.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. It is ugly
  2. It doesn’t work for me in next js. It says: TypeError: Cannot assign to read only property ‘size’ of object ‘#’

So I tried this way:

  adjustedConfig = { ...adjustedConfig, stars: { size: 20 } };

Here is a problem that it deletes other values in the nested object.

>Solution :

You need to use another ... in the nested object:

adjustedConfig = {...adjustedConfig, stars: {...adjustedConfig.stars, size: 20}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading