如何使用扩展语法创建或替换对嵌套对象的编辑?

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

对于简单的传播,我们可以像这样创建或替换:

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

我想做的是类似的东西,但在嵌套对象上:

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. 

我真正想要的结果是:

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

我将如何实现这一目标?

使用原始对象中的嵌套对象。并且只传播 属性

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

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

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 属性 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 属性 automatically at any level, there are a few light NPM packages like deep-assign. It works the same as assign but recursively.