对于简单的传播,我们可以这样创建或替换:
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"
}
};
我将如何实现?
答案 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.