Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do create or replace editing on a nested object with spread syntax?

For simple spreading we can do a create or replace like so:

let a = {1: "one", 2: "two"}; 
let b= {...a, ...{2: "too", 3: "three"}}
console.log(b); //{1: "one", 2: "too", 3: "three"}

What I want to do is, is something similar, but on a nested object:

let a = {
   title: "hello world", 
   nestedObject: {
      1: "one", 
      2: "two", 
   }
}; 

let b= {...a, ...{nestedObject: {2: "too", 3: "three"}}};
console.log(b); //Replaces the nested object entirely. 

What I actually want as a result is:

{
   title: "hello world", 
   nestedObject: {
      1: "one", 
      2: "too",
      3: "three" 
   }
}; 

How would I achieve this?

like image 933
dwjohnston Avatar asked Sep 16 '25 22:09

dwjohnston


1 Answers

I use this pattern in Redux reducers a lot. This is how I do it:

let a = {
   title: "hello world", 
   nestedObject: {
      1: "one", 
      2: "two", 
   }
}; 

let b = {
    ...a,
    nestedObject: {
        ...a.nestedObject, 
        2: "too",
        3: "three"
    }
};
console.log(b); //Replaces the nested object entirely. 

Note that I now use nestedObject as just a property name, and set it to a new object, which starts with ...a.nestedObject.

So, this means:

  • Add everything from a
  • Override nestedObject with a new object (because it comes AFTER ...a)
  • In the new object, add everything from a.nestedObject
  • Then add (and override any existing) props in nestedObject by props coming AFTER ...a.nestedObject

If you are looking for something that would override any property automatically at any level, there are a few light NPM packages like deep-assign. It works the same as assign but recursively.

like image 123
Meligy Avatar answered Sep 19 '25 08:09

Meligy