Skip to content

set

Set a value on an object using a path key

716 bytes
since v12.1.0

Usage

Opposite of get, dynamically set a nested value into an object using a key path. Does not modify the given initial object.

import * as
import _
_
from 'radashi'
import _
_
.
function set<{}, string>(initial: {}, path: string, value: string): {}

Opposite of get, dynamically set a nested value into an object using a key path. Does not modify the given initial object. Primitive intermediates are replaced with objects or arrays when a property needs to change.

@see ― https://radashi.js.org/reference/object/set

@example

set({}, 'name', 'ra') // => { name: 'ra' }
set({}, 'cards[0].value', 2) // => { cards: [{ value: 2 }] }

@version ― 12.1.0

set
({}, 'name', 'ra')
// => { name: 'ra' }
import _
_
.
function set<{}, number>(initial: {}, path: string, value: number): {}

Opposite of get, dynamically set a nested value into an object using a key path. Does not modify the given initial object. Primitive intermediates are replaced with objects or arrays when a property needs to change.

@see ― https://radashi.js.org/reference/object/set

@example

set({}, 'name', 'ra') // => { name: 'ra' }
set({}, 'cards[0].value', 2) // => { cards: [{ value: 2 }] }

@version ― 12.1.0

set
({}, 'cards[0].value', 2)
// => { cards: [{ value: 2 }] }

Primitive intermediates

When a path needs to write through an existing primitive value, that value is replaced with a plain object, or an array when the next path key is an integer. The original input is preserved.

import * as
import _
_
from 'radashi'
import _
_
.
function set<{
a: number;
}, number>(initial: {
a: number;
}, path: string, value: number): {
a: number;
}

Opposite of get, dynamically set a nested value into an object using a key path. Does not modify the given initial object. Primitive intermediates are replaced with objects or arrays when a property needs to change.

@see ― https://radashi.js.org/reference/object/set

@example

set({}, 'name', 'ra') // => { name: 'ra' }
set({}, 'cards[0].value', 2) // => { cards: [{ value: 2 }] }

@version ― 12.1.0

set
({
a: number
a
: 5 }, 'a.b', 1)
// => { a: { b: 1 } }
import _
_
.
function set<{
a: number;
}, number>(initial: {
a: number;
}, path: string, value: number): {
a: number;
}

Opposite of get, dynamically set a nested value into an object using a key path. Does not modify the given initial object. Primitive intermediates are replaced with objects or arrays when a property needs to change.

@see ― https://radashi.js.org/reference/object/set

@example

set({}, 'name', 'ra') // => { name: 'ra' }
set({}, 'cards[0].value', 2) // => { cards: [{ value: 2 }] }

@version ― 12.1.0

set
({
a: number
a
: 5 }, 'a[0]', 1)
// => { a: [1] }

An existing primitive can remain unchanged when the requested value already matches. For example, setting a.length to 3 on { a: 'str' } returns the original object.