Sets the value to an object at the given path.
Immutable: This does not mutate the original object.
Related
Syntax
import { toSet } from '@opentf/std'; toSet<T>( obj: T, path: string | unknown[], value: unknown | ((val: unknown) => unknown) ): T
The value param can be either any value or callback function.
The callback fn can be called with the property path value if it exist.
Missing intermediate branches are created automatically. Existing non-object intermediates such as 0, false, '', and null are preserved, and deep writes through them are ignored.
__proto__, constructor and prototype are refused as path segments. The path is checked before anything is written, so a refused path returns the original object untouched.
A numeric segment creates an array only up to MAX_ARRAY_INDEX (10,000). Above that the branch becomes a plain object keyed by the number, so the value is kept and only the array-ness is dropped.
A lone large index in untrusted input would otherwise build an array whose length makes serialising the result cost hundreds of megabytes. A flattened array starts at [0], so one of any size still round trips.
Examples
toSet({}, 'a', null) //=> { a: null } toSet({}, 'a', 1) //=> { a: 1 } toSet({}, 'a.b', 25) //=> { a: { b: 25 } } toSet({}, 'user.email', 'user@example.com') //=> // { // user: { email: 'user@example.com' } // } toSet({}, '0', 'Apple') //=> { '0': 'Apple' } toSet({}, 'fruits[0]', 'Apple') //=> { fruits: ['Apple'] } toSet({ a: 1 }, 'a', (val) => val + 1) //=> { a: 2 } const fn = () => render('My Component') toSet({ subscribeFns: [] }, 'subscribeFns[0]', () => fn) //=> { subscribeFns: [fn] } toSet({ a: false }, 'a.b', 1) //=> { a: false }