Dev Helpers
← Back

Replace a matching record immutably

Replace a matching record immutably using TypeScript.

Open this example in the interactive library

Source code

type Item = Readonly<{ id: number; label: string }>;
const items: readonly Item[] = [
  { id: 1, label: "one" },
  { id: 2, label: "two" },
];
console.log(
  items.map((item) => (item.id === 2 ? { ...item, label: "updated" } : item)),
);

Sample output

[ { id: 1, label: 'one' }, { id: 2, label: 'updated' } ]