Skip to main content

Function: setAtPath()

setAtPath(target, path, value): Record<string, unknown>

Defined in: packages/core/src/setAtPath.ts:34

Writes a value at a dotted path in a plain object, copying every level the path passes through. setNodeProp edits props with it, and the renderer fills a resolved hole with it.

The path is .-separated object keys — price, cta.link.label. Each segment names a key, never an array index: a numeric segment is the key "0", and an array met on the way down is refused rather than descended into. The last segment is written wholesale, so an array or object already sitting there is replaced entire. An intermediate key holding no object — a missing key, null, a string, a number — is replaced by a fresh object.

Parameters

target

Record<string, unknown>

The object to write into. Read, never written.

path

string

Dotted path of object keys. Every segment must be non-empty and free of [].

value

unknown

What to write at the path. Anything, including undefined.

Returns

Record<string, unknown>

A new record with the path written. The argument is not mutated: each level along the path is a fresh object, and every key off the path is carried over by reference.

Throws

path-not-addressable when a segment is empty, carries [] — which names every member of an array rather than one target — or descends into an array.

Example

setAtPath({ title: "T", price: 0 }, "price", 42); // { title: "T", price: 42 }
setAtPath({}, "cta.price", 42); // { cta: { price: 42 } } — intermediates are created
setAtPath({ cta: "text" }, "cta.price", 42); // { cta: { price: 42 } } — the string is gone
setAtPath({ items: ["a", "b"] }, "items", ["c"]); // { items: ["c"] } — a whole-field write

setAtPath({ items: ["a", "b"] }, "items.0", "X"); // throws — `items` is an array
setAtPath({}, "items[].price", 42); // throws — `[]` names every member, not one