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}

warning 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);