Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Set a Field

Immutable Stateeasy

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

Implement `setField(state, key, value)` returning a new object with `key` set to `value`.

Sample tests

Input: setField({"a":1}, "b", 2)
Output: {"a":1,"b":2}
Input: setField({"a":1}, "a", 9)
Output: {"a":9}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Assigning state[key] = value mutates the object React is holding.

Learning resources

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

Returning { ...state, [key]: value } creates a new object with one field changed, giving React a new reference to detect the update.

Loading...
⌘/Ctrl + Enter

Run your code to see results.