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.

  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}}

Leave a Reply