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?
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:
a
nestedObject
with a new object (because it comes AFTER ...a
)a.nestedObject
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With