How to Update an Object in an Array in TypeScript?

Recently, one of my team members asked me how to update a specific object within an array in TypeScript, a common task that can be handled in several efficient ways. Whether you’re working with simple objects or dealing with more complex structures, understanding how to correctly update an item in an array is essential for maintaining clean and predictable data handling in your applications.

In this tutorial, I’ll explain how to update an object in an array using TypeScript, with the help of practical examples and explanations.

The Problem: Updating an Object in an Array

Let’s say you have an array of objects representing users in your application. Each user object has properties like name, age, and email. Now, you need to update a specific user’s information based on their ID. How can you accomplish this in TypeScript?

Consider the following example:

interface User {
  id: number;
  name: string;
  age: number;
  email: string;
}

const users: User[] = [
  { id: 1, name: 'John Doe', age: 25, email: 'john@example.com' },
  { id: 2, name: 'Jane Smith', age: 30, email: 'jane@example.com' },
  { id: 3, name: 'Mike Johnson', age: 35, email: 'mike@example.com' },
];

Now, let’s say you want to update the email of the user with id 2. How can you achieve this?

Method 1: Using the map Function

One approach to update an object in an array is by using a map function. The map function creates a new array by calling a provided function on every element in the original array.

Here’s an example:

const updatedUsers = users.map(user => {
  if (user.id === 2) {
    return { ...user, email: 'jane.smith@example.com' };
  }
  return user;
});

Output:

Update an Object in an Array in TypeScript

In this code, we use the map function to iterate over each user object in the users array. If the id of the user matches the desired id (in this case, 2). Then, we create a new object using the spread operator (…) to copy the existing properties and override the email property with the updated value. For all other users, we simply return the original user object.

Method 2: Using the findIndex Function and Index Assignment

Another approach is to use the findIndex function to locate the index of the object you want to update, and then directly assign the updated object to that index in the array.

Here’s an example:

const index = users.findIndex(user => user.id === 2);
if (index !== -1) {
  users[index] = { ...users[index], email: 'jane.smith@example.com' };
}

Output:

update object array using find index in typescript

In this code, we use the findIndex function to find the index of the user object with id 2. If the index is found (i.e., not -1), we directly assign a new object to that index in the users array. The new object is created using the spread operator (…) to copy the existing properties and override the email property with the updated value.

Method 3: Creating a Generic Update Function

If you find yourself frequently updating objects in arrays, you can create a generic function to handle the update operation. This function can take the array, the object to update, and a predicate function to determine which object to update.

Here’s an example of a generic update function:

function updateObjectInArray<T>(
  array: T[],
  objectToUpdate: Partial<T>,
  predicate: (obj: T) => boolean
): T[] {
  return array.map(obj => {
    if (predicate(obj)) {
      return { ...obj, ...objectToUpdate };
    }
    return obj;
  });
}

In this code, the updateObjectInArray function takes three parameters:

  • array: The array containing the objects to be updated.
  • objectToUpdate: An object with the properties to be updated. It uses the Partial<T> type to allow partial updates.
  • predicate: A function that determines which object in the array should be updated. It takes an object as input and returns a boolean value.

The function uses the map method to iterate over each object in the array. If the predicate function returns true for an object, it creates a new object using the spread operator (…) to merge the existing properties with the properties from objectToUpdate. Otherwise, it returns the original object.

Here’s an example of how to use the generic update function:

const updatedUsers = updateObjectInArray(
  users,
  { email: 'jane.smith@example.com' },
  user => user.id === 2
);

Output:

How to update object array in typescript

In this code, we call the updateObjectInArray function, passing in the users array, an object with the updated email property, and a predicate function that checks if the id of user is 2. The function returns a new array with the updated user object.

Real-World Example: Updating User Profiles

Let’s consider a real-world scenario where you have an application that allows users to update their profile information. Each user object in the array represents a user profile with properties like name, age, email, and address.

interface User {
  id: number;
  name: string;
  age: number;
  email: string;
  address: string;
}

const users: User[] = [
  { id: 1, name: 'John Doe', age: 25, email: 'john@example.com', address: '123 Main St, New York, NY' },
  { id: 2, name: 'Jane Smith', age: 30, email: 'jane@example.com', address: '456 Elm St, Los Angeles, CA' },
  { id: 3, name: 'Mike Johnson', age: 35, email: 'mike@example.com', address: '789 Oak St, Chicago, IL' },
];

Now, let’s say a user with id 2 wants to update their email and address. You can use the generic update function we created earlier to handle this update:

const updatedUsers = updateObjectInArray(
  users,
  { email: 'jane.smith@example.com', address: '987 Pine St, San Francisco, CA' },
  user => user.id === 2
);

Output:

Update an Array value in Typescript

In this code, we call the updateObjectInArray function, passing in the users array, an object with the updated email and address properties, and a predicate function that checks if the id of user is 2. The function returns a new array with the updated user object.

Updating objects in arrays is a common task in TypeScript applications, especially when dealing with user profiles, product catalogs, or any scenario where you need to modify specific objects within an array.

Conclusion

In this Typescript tutorial, we have learned the ways to update an object inside an array. We used the map() method to create a new array with the updated object, the findIndex() method to locate and update the object directly, and also created a generic update function for reusability.

It’s important to know when you’re changing the original array or returning a new one. The map() method and the generic function return a new array, while updating by index changes the original array. These techniques are helpful when you’re working with things like user profiles, product lists, or any data stored as objects in arrays..

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.