Set Nested Value
MediumUtility Functions15 min4 tests
Implement a setNested function that sets a value at a deeply nested path in an object, creating intermediate objects as needed.
Requirements
- Accept a dot-separated path string (e.g.,
"a.b.c") - Create intermediate objects if they don't exist
- Overwrite the value at the final key
- Mutate and return the original object
Example
setNested({}, 'a.b.c', 42); // { a: { b: { c: 42 } } }
setNested({ a: { x: 1 } }, 'a.y', 2); // { a: { x: 1, y: 2 } }Hints (4)
- Split the path string by "." to get an array of keys.
- Walk through the keys, creating objects along the way if needed.
- Stop one key before the end to set the final value.
- Return the original object after mutation.
Topics
- Utility Functions
Asked at
Google · Meta · Uber
