set
Sets a nested value in an object using a dot-separated path. Creates nested objects as needed.
1/**
2 * Sets a nested value in an object using a dot-separated path.
3 * Creates nested objects as needed.
4 *
5 * @param obj - The target object to modify.
6 * @param path - The dot-separated path string (e.g. "a.b.c").
7 * @param value - The value to set at the given path.
8 */
9export function set(obj: any, path: string, value: any): void {
10 if (typeof path !== 'string' || !path.length) return;
11
12 const keys = path.split('.');
13 let current = obj;
14
15 for (let i = 0; i < keys.length - 1; i++) {
16 const key = keys[i];
17 if (
18 current[key] === undefined ||
19 typeof current[key] !== 'object' ||
20 current[key] === null
21 ) {
22 current[key] = {};
23 }
24 current = current[key];
25 }
26
27 current[keys[keys.length - 1]] = value;
28}
Nested Structure Creation
Automatically creates intermediate objects along the path if they don’t exist, enabling safe deep updates.
Dot-Notation Support
Allows setting deeply nested values using a simple string path like
"a.b.c"
, improving readability and flexibility.Mutation-Friendly
Directly modifies the original object, which is efficient and often desirable in controlled environments.
Type-Agnostic and Null-Safe
Handles
undefined
andnull
gracefully, avoiding common pitfalls with deep property assignment.
Tests | Examples
1test('set - sets a deeply nested value', () => {
2 const obj = {};
3 set(obj, 'a.b.c', 42);
4 expect(obj).toEqual({ a: { b: { c: 42 } } });
5});
6
7test('set - overrides existing value', () => {
8 const obj = { a: { b: { c: 10 } } };
9 set(obj, 'a.b.c', 99);
10 expect(obj.a.b.c).toBe(99);
11});
12
13test('set - creates missing intermediate objects', () => {
14 const obj = {};
15 set(obj, 'x.y.z', 'value');
16 expect(obj).toEqual({ x: { y: { z: 'value' } } });
17});
18
19test('set - handles single-level path', () => {
20 const obj = {};
21 set(obj, 'key', 123);
22 expect(obj.key).toBe(123);
23});
24
25test('set - does nothing for empty path', () => {
26 const obj = { a: 1 };
27 set(obj, '', 'ignored');
28 expect(obj).toEqual({ a: 1 });
29});
30
31test('set - overwrites non-object intermediate values', () => {
32 const obj = { a: null };
33 set(obj, 'a.b', 5);
34 expect(obj).toEqual({ a: { b: 5 } });
35});
Common Use Cases
Dynamic State Updates
Update nested state properties in frameworks like Vue, React, or MobX without manual object construction.
Form and Validation Management
Programmatically set deeply nested form values, errors, or touched flags.
Configuration Manipulation
Modify nested configuration objects or environment structures based on user input or runtime changes.
Data Normalization or Preparation
Populate complex JSON structures before sending data to APIs or databases.
Scripting and Automation
Dynamically modify object trees in utility scripts, CLI tools, or data transformers.