Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Update a Nested Field

Immutable Statemedium

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

State often nests objects, e.g. `{ user: { name, age }, theme }`. Implement `updateUserField(state, field, value)` returning a new state object with `state.user[field]` replaced, without mutating the original.

Sample tests

Input: updateUserField({"user":{"name":"A","age":1},"theme":"dark"}, "age", 2)
Output: {"user":{"name":"A","age":2},"theme":"dark"}
Input: updateUserField({"user":{"name":"x"}}, "name", "y")
Output: {"user":{"name":"y"}}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating state.user directly changes the original object even if you return a new outer object.
  • Only spreading the outer level leaves user pointing at the same nested object.

Learning resources

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

Immutable nested updates copy every level on the path to the change. Spreading state copies the top level, spreading state.user copies the nested object, and the computed key [field] overrides just the targeted property.

Loading...
⌘/Ctrl + Enter

Run your code to see results.