Skip to main content

update()

update<T>(object, path, updater): T

Updates the value at path of object using an updater function, returning a new object (immutable).

πŸ’Ž Why is this a Hidden Gem?

Apply a transformation to a deeply nested value without touching the rest.

DEPRECATED

Use set(obj, path, fn(get(obj, path))) directly instead.


Type Parameters​

T: T extends object​

The type of the input object.


Parameters​

object: T​

The object to modify.

path: string | (string | number | symbol)[]​

The path of the property to update.

updater: (value) => unknown​

The function to produce the updated value.


Returns: T​

A new object with the updated value.


See Also​


Since​

2.0.0


Also known as​

update (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example​

const object = { a: { b: { c: 3 } } };

// ❌ Deprecated approach
update(object, 'a.b.c', n => n * 2);
// => { a: { b: { c: 6 } } }

// βœ… Recommended approach
set(object, 'a.b.c', get(object, 'a.b.c') * 2);
// => { a: { b: { c: 6 } } }

// Or with optional chaining for simple cases
const value = object.a?.b?.c ?? 0;
set(object, 'a.b.c', value * 2);

How it works?​

Updates value at path using updater function (immutable).

Processing Flow​

Common Inputs​

ObjectPathUpdaterResult
{a: {b: 3}}'a.b'n => n * 2{a: {b: 6}}
{count: 0}'count'n => n + 1{count: 1}

Deprecated: Use set(obj, path, fn(get(obj, path))) directly.


Use Cases​

Update nested value πŸ“Œβ€‹

Update value at path with function.

import { get, set } from '@pithos/arkhe';
const updated = set(obj, 'a.b.c', get(obj, 'a.b.c') * 2);

Increment counter​

Update nested counter.

import { get, set } from '@pithos/arkhe';
const path = 'stats.views';
const newState = set(state, path, (get(state, path) as number) + 1);