dset is a tiny utility for writing values into deeply nested objects and arrays.
Implement a simplified deepSet(obj, path, value) function.
The function should mutate obj in place by writing value at path. If part of the path does not exist yet, create the missing objects or arrays along the way.
Write into nested objects.
const object = { user: { profile: { name: 'John' } } };deepSet(object, 'user.profile.age', 30);// {// user: {// profile: {// name: 'John',// age: 30,// },// },// }
Write into arrays using numeric path segments.
const object = { items: ['a', 'b', 'c'] };deepSet(object, 'items.1', 'updated');// { items: ['a', 'updated', 'c'] }
Create mixed object/array structures when needed.
const object = {};deepSet(object, 'a.0.b.1', 2);// {// a: [// {// b: [undefined, 2],// },// ],// }
If traversal needs to continue through a primitive value, replace that branch with a new container.
const object = { config: true };deepSet(object, 'config.theme.name', 'dark');// {// config: {// theme: {// name: 'dark',// },// },// }
deepSet(obj, path, value)
obj (object | Array<unknown>): The object to mutate.path (string | Array<string | number>): The path where the value should be written.
. as the separator, such as 'user.profile.name'.['user', 'profile', 'name'] or ['items', 0, 'label'].value (unknown): The value to write at the target path.a[0].b is out of scope.Implement Deep Set II to merge object and array values at the leaf instead of always overwriting them.
console.log() statements will appear here.