The set function modifies an object by setting a value at a specified path. If any part of the path does not exist, the function automatically creates the necessary structure (either an object or an array) to reach the target location.
Key Behaviors:
- Path Syntax: Uses dot notation (e.g.,
a.b.c) or bracket notation for array indices (e.g., a.c[0]). - Array Creation: If a path segment uses bracket notation (e.g.,
[0]) and the parent property is not already an array, set will initialize it as an array. - Object Creation: If a path segment uses dot notation and the parent property is not a plain object,
set will initialize it as an object. - Numeric Keys: Numbers separated by dots (e.g.,
a.0.b) are treated as object keys rather than array indices. - Security: The function explicitly ignores paths containing
__proto__ to prevent prototype pollution. - Error Handling: Throws an error if the provided path does not match the expected format.
const obj = { a: { b: 2 } };
// Set a nested property
set(obj, 'a.c', 1);
// => { a: { b: 2, c: 1 } }
// Use bracket notation for arrays
set(obj, 'a.c[0]', 'hello');
// => { a: { b: 2, c: ['hello'] } }
// Numbers with dots are treated as object keys
set(obj, 'a.c.0.d', 'world');
// => { a: { b: 2, c: { 0: { d: 'world' } } } }
// Numbers in keys are supported
set(obj, 'a.e0.a', 1);
// => { a: { e0: { a: 1 } } }