Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Update Nested Field

Immutable Statehard

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 111: The Spread Operator (...)

Implement `updateNested(state, path, value)` where `path` is an array of keys, returning a new object with the nested value replaced and no mutation of the original.

Sample tests

Input: updateNested({"user":{"name":"a"}}, ["user","name"], "b")
Output: {"user":{"name":"b"}}
Input: updateNested({"a":{"b":{"c":1}}}, ["a","b","c"], 9)
Output: {"a":{"b":{"c":9}}}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating a nested object mutates shared state, since spread only copies the top level.
  • Forgetting to spread an intermediate level leaves it pointing at the old nested object.

Learning resources

  • React: Updating Objects in State
Approach & explanation (try first)

Each level returns a new object that spreads its siblings and replaces only the one child on the path. Recursing to the leaf and rebuilding every parent keeps the whole path immutable.

Loading...
⌘/Ctrl + Enter

Run your code to see results.