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

dwj*_*ton 4 javascript destructuring spread-syntax

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

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

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

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. 
Run Code Online (Sandbox Code Playgroud)

我真正想要的结果是:

{
   title: "hello world", 
   nestedObject: {
      1: "one", 
      2: "too",
      3: "three" 
   }
}; 
Run Code Online (Sandbox Code Playgroud)

我将如何实现这一目标?

Mel*_*igy 6

我在 Redux 减速器中经常使用这种模式。我就是这样做的:

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. 
Run Code Online (Sandbox Code Playgroud)

请注意,我现在仅用作nestedObject属性名称,并将其设置为一个以 . 开头的新对象...a.nestedObject

所以,这意味着:

  • 添加所有内容a
  • nestedObject用新对象覆盖(因为它出现在 AFTER 之后...a
  • 在新对象中,添加以下所有内容a.nestedObject
  • nestedObject然后通过之后出现的道具添加(并覆盖任何现有的)道具...a.nestedObject

如果您正在寻找可以在任何级别自动覆盖任何属性的东西,有一些轻量级的 NPM 包,例如deep-assign。它的工作原理与递归相同assign