Immutably patch JS objects.

Usage no npm install needed!

<script type="module">
  import akbrPatchInto from 'https://cdn.skypack.dev/@akbr/patch-into';


patchInto :wrench:

Immutably patch JS objects.

Supports nesting and caching.

Intended as a low-level function. If you are interested in immutably revising JS objects, see akbr/revise for more features.


var obj = {hello: "world"};

// A simple revision
var obj2 = patchInto(obj, "foo", "bar");
obj2 // {hello: "world", foo: "bar"}
obj1 // {hello: "world"}

// Burrow in
var obj3 = patchInto(obj, ["a", "b", "c"], "baz");
obj3 // {hello: "world", a:{b:{c:"baz"}}}}
obj1 // {hello: "world"}

// For multi-step operations, cache can speed things up.
var universe = {
  galaxies: {
    1: {
      name: "Milky Way"
    //, ... 500

var cache = {};
var universe2 = patchInto(universe, ["galaxies", 1, "numStars"], 100000000000, cache);
// Cache now indicates that "galaxies" and "1" have already been copied, and are thus "safe" for future mutation (w/r/t the original universe object).
// If we pass this cache to another operation, we avoid creating redundant shallow copies.
universe2 = patchInto(universe2, ["galaxies", 1, "isInhabitedBy"], ["humans", "martians"], cache);


patchInto(obj, path, value[, cache])

obj: an object or array.


  • A string, dot notation for nesting;
  • A number;
  • An array, multiple values for nesting.

Other path types are interpreted as an empty path.

value: anything.

cache: an empty object (for a new cache) or a previous cache object. pathInto mutates cache objects so they are cumulative over multiple operations.


1.0.1 - Invalid paths now interpreted as an empty path.