Say I have a "base" object like this:
{
foo: {
bar: {
baz: 123
},
hello: 'world',
something: {
deeply: {
nested: true
}
}
}
}
Then say I want to "extend" that nested object with another object, thereby "adding" properties to the base object, but without mutably changing it, and without also just recreating every object in the tree! It should be somewhat optimized by only recreating objects which need to be recreated, so only doing { ...x }
where it needs to be done because we are changing something...
So say I extend our base object with an "updates" object that looks like this:
{
foo: {
hello: 'earth',
something: {
deeply: {
iAmNew: 32134
}
}
}
}
The end result is obviously this:
{
foo: {
bar: {
baz: 123
},
hello: 'earth',
something: {
deeply: {
nested: true,
iAmNew: 32134
}
}
}
}
But it should not recreate the { baz: 123 }
object, because nothing changed there.
In my situation, I have a complex, deeply nested (up to eight levels deep) settings object. So if every time you changed a setting it recreated this whole object, that seems inefficient. It should just change the parts that change, while leaving the rest intact.
Can it be done easily?
export function extend(
start,
updates,
) {
const end = { ...start }
let node = end
for (const i in updates) {
const val = updates[i]
if (val != null) {
if (typeof val === 'object') {
}
}
}
return end
}