Reducers and state containers often need to update a deeply nested field without mutating the existing state. Writing the full object-spread chain by hand works, but it quickly becomes noisy.
An easy way to update an object while leaving the original untouched would be to deeply clone it, but that uses much more memory because each update creates an entirely new object, which is wasteful when most values in the original object usually stay the same.
Implement a function objectUpdate(source, path, value) that updates a nested object path in an immutable fashion and returns a new object instance while sharing the original inner structure where possible.
This question is intentionally scoped:
source is a plain JavaScript object.path is a non-empty dot-delimited string such as 'draft.user.name'.Return a new object where the value at path has been replaced with value.
The important constraint is structural sharing:
const state = {draft: {user: {name: 'Alice',role: 'admin',},meta: {saved: false,},},theme: {mode: 'dark',},};const next = objectUpdate(state, 'draft.user.name', 'Bob');next.draft.user.name; // 'Bob'next !== state; // truenext.draft !== state.draft; // truenext.draft.user !== state.draft.user; // truenext.draft.meta === state.draft.meta; // truenext.theme === state.theme; // true
const state = {status: 'draft',draft: {title: 'Object Update',},};const next = objectUpdate(state, 'status', 'published');console.log(next); // { status: 'published', draft: { title: 'Object Update' } }console.log(state.status); // 'draft'
objectUpdate(source, path, value) accepts the following arguments:
| Argument | Type | Description |
|---|---|---|
source | Object | The plain object to update. |
path | string | A non-empty dot-delimited path pointing to an existing nested property. |
value | unknown | The new value to store at the final path segment. |
Returns a new object with the updated value written at path.
source.Implement Object Update II to support arrays, updater callbacks, and creating missing object branches.
console.log() statements will appear here.