This JavaScript code defines a function named set that is used to set a value in a nested object structure based on a provided path. Let's break down what the function does step by step:
Function Signature:
export default function set(obj, path, value) {
// Function body
}
obj: The object in which you want to set a value.
path: An array representing the nested path to the property where the value should be set. For example, ['a', 'b', 'c'] would target obj.a.b.c.
value: The value to be set at the specified path.
Function Logic:
-
Input Validation:
if (!Array.isArray(path)) throw new Error('Not an array');
- Ensures that
path is an array. If not, it throws an error.
-
Base Case:
if (path.length === 0) return value;
- If the
path array is empty, the function returns the value immediately. This acts as a base case for recursion.
-
Handle Null or Undefined Object:
if (obj === null || obj === undefined) {
obj = {}; // eslint-disable-line no-param-reassign
}
- If
obj is null or undefined, it initializes obj as an empty object. This ensures that the function can handle cases where the object doesn't exist yet.
-
Type Check for obj:
if (typeof obj !== 'object') {
console.error(`Cannot set property ${JSON.stringify(path)} of ${typeof obj} ${obj}`);
}
- If
obj is not an object (e.g., it's a primitive type like a string or number), it logs an error to the console. This is because you can't set properties on non-objects.
-
Destructure the Path:
const [propName, ...subpath] = path;
- Extracts the first element of the
path array as propName (the current property to set) and the remaining elements as subpath (the nested path for recursive calls).
-
Clone the Object:
const res = clone(obj);
- Creates a clone of the original
obj to avoid mutating it directly. The clone function is assumed to be defined elsewhere and is responsible for creating a deep copy of the object.
-
Recursive Call:
res[propName] = set(obj[propName], subpath, value);
- Recursively calls the
set function on the nested object (obj[propName]) with the remaining subpath and the value. The result of this recursive call is assigned to res[propName].
-
Return the Result:
return res;
- Returns the modified object (
res) with the value set at the specified path.
Example Usage:
const obj = { a: { b: { c: 1 } } };
const result = set(obj, ['a', 'b', 'c'], 2);
console.log(result); // { a: { b: { c: 2 } } }
Key Points:
- Immutability: The function avoids mutating the original object by cloning it.
- Recursion: It uses recursion to traverse nested paths.
- Error Handling: It includes checks for invalid inputs and logs errors for unsupported operations.
This function is useful for safely setting values in deeply nested objects without modifying the original object.