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)
  1. Split the path string by "." to get an array of keys.
  2. Walk through the keys, creating objects along the way if needed.
  3. Stop one key before the end to set the final value.
  4. Return the original object after mutation.

Topics

  • Utility Functions

Asked at

Google · Meta · Uber

Join Us
blur