Update a nested value at a path without mutating the source
State libraries such as Redux require updates that never mutate the previous state. Writing those updates by hand for deeply nested data means a long chain of spreads. Implement updateIn(source, path, update), which returns a new version of source with the value at path replaced, without touching the original.
updateIn(source, path, update) // => new root (or source itself if nothing changed)
source: any value, usually a tree of plain objects and arrays.path: an array of keys. Strings are object keys and numbers are array indexes, for example ['board', 'columns', 2, 'title'].update: if it is a function, it is called once with the current value at path (undefined if missing), and its return value becomes the new value. Otherwise update itself is the new value. (To store a function, pass () => fn.)source or any object or array inside it.undefined, or null, create it: an array when the key used to index into it is a number, otherwise a plain object.null or undefined), throw a TypeError.Object.is, return source itself and create no copies. A missing value counts as undefined.path = [], the update applies to source itself.const state = {
user: { name: 'Rae', tags: ['admin'] },
board: { columns: [{ title: 'Todo', cards: 3 }, { title: 'Done', cards: 8 }] },
};
const next = updateIn(state, ['board', 'columns', 1, 'cards'], (n) => n + 1);
next.board.columns[1].cards; // => 9
state.board.columns[1].cards; // => 8 (unchanged)
next.user === state.user; // => true (not on the path)
next.board.columns[0] === state.board.columns[0]; // => true
Array.isArray(next.board.columns); // => true
updateIn({}, ['settings', 'shortcuts', 0], 'ctrl+k');
// => { settings: { shortcuts: ['ctrl+k'] } }
updateIn({ theme: null }, ['theme', 'mode'], 'dark');
// => { theme: { mode: 'dark' } }
updateIn(state, ['user', 'name'], 'Rae') === state; // => true (no change)
updateIn({ count: 3 }, ['count', 'value'], 1);
// throws TypeError (count is a number)
updateIn(5, [], (n) => n * 2); // => 10
Map, and Set do not appear on paths.slice), not as objects.