← React / TypeScript

React / TypeScript · 06 / 18

Arrays, objects and new values

Describe records and create changes without overwriting the old value.

  • Small
  • Basics
  • 15 min

Prerequisites: Functions and scope

An object associates named properties with values. An array holds an ordered list. Together they can describe house records and entries. React later compares state values. It therefore helps to create a new object or array for a change rather than secretly mutating the existing value.

Example files

01Read properties

entry.title reads the title property. Curly braces containing name-value pairs create an object. An ID identifies a record independently of its potentially changing title.

objects.mjs · javascriptOpen file
const entry = { id: 'e1', title: 'Roof', costCents: 12990 };
const updated = { ...entry, title: 'Roof repair' };
const entries = [entry];
const next = entries.map((item) => item.id === updated.id ? updated : item);
console.log(entry.title);
console.log(next[0].title);

Run / check

node objects.mjs

02Create a new version

...entry copies the top-level properties into a new object. The following title property replaces only that value. This copy is shallow. Nested objects also require deliberate copying when changed.

03Transform a list

map produces a result from each item and returns a new array. We replace only the item with the matching ID. filter would be appropriate for removing items. Neither changes the original array.

Expected result

Old object: Roof. New object: Roof repair.

Your exercise

Create an array from next without entry e1.

Show the solution and explanation

const remaining = next.filter((item) => item.id !== "e1") produces an empty array. next still contains the updated entry. The result must later be deliberately used as the new state.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.