setPath
Set a value at a dot or bracket path inside an object, creating intermediate objects as needed and returning the updated object.
Usage
setPath writes a value at a specified path inside an object.
import { setPath } from '@movk/core'
const obj: any = {}
setPath(obj, 'a.b[0].c', 7)
// obj => { a: { b: [{ c: 7 }] } }
setPath(obj, 'a.b[2].d', 8)
// Array is automatically extended to length 3
// obj.a.b[2] => { d: 8 }
setPath(obj, 'a.0.b', 1) // Numeric keys in dot notation remain as string keys
// obj => { a: { 0: { b: 1 } } }
setPath(obj, 'a[0].b', 2) // Use bracket notation for array indices
// obj.a[0].b => 2
API
setPath(object, path, value)
Write a value at a specified path inside an object.
Parameters
object
T required
The target object (mutated in place and returned as the same reference).
path
PathInput required
A path string or array of segments.
value
unknown required
The value to write.
Returns
returns
T
The original object (mutated).
Changelog
No recent changes