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

时间:2018-10-15 05:18:45

标签: 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"}

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

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

我将如何实现?

2 个答案:

答案 0 :(得分:2)

我在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. 

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

所以,这意味着:

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

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

答案 1 :(得分:1)

使用原始对象中的嵌套对象。而且只能传播该财产

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.