Dynamically Set Object Properties by Path in JavaScript
Many applications require manipulating deeply nested objects without knowing the exact structure beforehand. This challenge asks you to write a function that can set a property on an object at a specified path, creating intermediate objects as needed. This is useful for configuration management, data transformation, and dynamic object updates.
Problem Description
You are tasked with creating a JavaScript function called setPath. This function should accept three arguments: an object (obj), a string representing the path to the property (path), and the value to set (value). The path will be a string containing dot-separated property names (e.g., "a.b.c").
The function should traverse the object based on the provided path. If any intermediate property in the path does not exist, it should be created as an empty object. Finally, it should set the value at the specified path.
Key Requirements:
- The function must handle paths of varying lengths.
- It must create intermediate objects if they don't exist.
- It should not modify the original object if the path is empty.
- It should handle cases where the input object is null or undefined gracefully (treat as an empty object).
Expected Behavior:
The function should modify the object in place and return the modified object.
Edge Cases to Consider:
- Empty path: Should not modify the object.
- Null or undefined object: Should treat as an empty object.
- Path with leading or trailing dots.
- Path with consecutive dots.
- Path containing numbers or special characters (treat as regular property names).
Examples
Example 1:
Input: obj = { a: { b: 1 } }, path = "a.b.c", value = 2
Output: { a: { b: 1, c: 2 } }
Explanation: The function sets the value of 'c' within the 'b' object, which is within the 'a' object.
Example 2:
Input: obj = {}, path = "x.y.z", value = "hello"
Output: { x: { y: { z: 'hello' } } }
Explanation: The function creates the 'x', 'y', and 'z' properties as needed and sets the value of 'z' to "hello".
Example 3:
Input: obj = { a: 1 }, path = "a.b.c", value = null
Output: { a: 1, b: { c: null } }
Explanation: The function creates 'b' and 'c' and sets 'c' to null.
Example 4:
Input: obj = { a: { b: 1 } }, path = "", value = 2
Output: { a: { b: 1 } }
Explanation: Empty path, no modification.
Constraints
- The
pathstring will contain only alphanumeric characters and dots (.). - The
objcan be any JavaScript object, includingnullorundefined. - The
valuecan be any valid JavaScript value. - The function must be performant enough to handle paths up to 20 levels deep without significant performance degradation.
Notes
Consider using split() to break down the path into individual property names. Iterating through the path and creating objects as needed is a common approach. Remember to handle the edge cases carefully to ensure the function behaves as expected in all scenarios. Think about how to handle the initial object being null or undefined.