Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

TypeScript: Array of Objects

5 min readOct 17, 2024

--

Press enter or click to view image in full size
TypeScript, a statically typed superset of JavaScript, offers features that enhance development by adding strong typing. One of the most commonly used features in TypeScript is working with arrays, especially arrays of objects. Arrays allow developers to store multiple values in a single variable, and objects are useful for representing structured data.

TypeScript, a statically typed superset of JavaScript, offers features that enhance development by adding strong typing.

One of the most commonly used features in TypeScript is working with arrays, especially arrays of objects.

Arrays allow developers to store multiple values in a single variable, and objects are useful for representing structured data.

In this blog, we’ll explore how to work with arrays of objects in TypeScript and demonstrate their usage through various examples.

Why Use Arrays of Objects?

In many applications, you often need to store and manipulate data that has a more complex structure than just a list of strings or numbers.

An array of objects allows you to store a collection of objects, where each object can represent data with multiple properties.

For example, you might use an array of objects to store a list of users, products, or blog posts, each containing multiple fields like name, price, or author.

Declaring an Array of Objects in TypeScript

In TypeScript, you can declare an array of objects in multiple ways. Below is the simplest way to declare an array of objects:

let users: { name: string; age: number; isActive: boolean; }[] = [
{ name: "Alice", age: 25, isActive: true },
{ name: "Bob", age: 30, isActive: false },
{ name: "Charlie", age: 35, isActive: true }
];

Breakdown:

  • users is an array of objects where each object has three properties: name, age, and isActive.
  • The property types are defined as name (string), age (number), and isActive (boolean).
  • The array contains three objects representing users.

Using Type Aliases for Arrays of Objects

To make your code more reusable and maintainable, you can define a type alias for your object structure. This can be particularly helpful when you need to declare multiple arrays or objects with the same structure.

type User = {
name: string;
age: number;
isActive: boolean;
};

let users: User[] = [
{ name: "Alice", age: 25, isActive: true },
{ name: "Bob", age: 30, isActive: false },
{ name: "Charlie", age: 35, isActive: true }
];

Example Operations on an Array of Objects

Let’s explore common operations on an array of objects, such as adding new objects, updating existing ones, and filtering based on certain conditions.

1. Adding a New Object to the Array

You can easily add a new object to the array using the push() method.

users.push({ name: "Dave", age: 28, isActive: true });
console.log(users);

This will append a new object representing the user “Dave” to the users array.

2. Finding an Object in the Array

You can use the find() method to locate a specific object in the array based on one or more conditions.

const user = users.find(user => user.name === "Alice");
console.log(user);

This will return the object for “Alice” if found, or undefined if not.

3. Filtering the Array Based on Conditions

To retrieve a subset of the array based on a specific condition, you can use the filter() method. For example, you might want to filter the users who are active.

const activeUsers = users.filter(user => user.isActive);
console.log(activeUsers);

This returns an array of users who have isActive set to true.

4. Updating an Object in the Array

To update an object in the array, you can find it by its property and then modify the values of its properties.

const updateUser = users.find(user => user.name === "Bob");
if (updateUser) {
updateUser.isActive = true;
}
console.log(users);

In this example, we find the user named “Bob” and update their isActive status to true.

5. Deleting an Object from the Array

You can remove an object from the array using the splice() method if you know the index of the object you want to delete.

const index = users.findIndex(user => user.name === "Charlie");
if (index !== -1) {
users.splice(index, 1);
}
console.log(users);

This code finds the index of “Charlie” in the users array and removes the object.

Iterating Over an Array of Objects

You can use loops to iterate over arrays of objects, allowing you to access and manipulate each object within the array. The most common way to iterate is with a forEach loop.

users.forEach(user => {
console.log(`${user.name} is ${user.age} years old and is ${user.isActive ? 'active' : 'inactive'}.`);
});

This will print the details of each user in the array.

More Complex Arrays of Objects: Nested Objects

Sometimes, the objects you store in an array may have other nested objects or arrays as properties. Let’s consider an example where each user has a list of hobbies.

type User = {
name: string;
age: number;
isActive: boolean;
hobbies: string[];
};

let users: User[] = [
{ name: "Alice", age: 25, isActive: true, hobbies: ["reading", "swimming"] },
{ name: "Bob", age: 30, isActive: false, hobbies: ["cycling", "hiking"] },
{ name: "Charlie", age: 35, isActive: true, hobbies: ["gaming", "coding"] }
];

console.log(users);

In this example, each user object now has an additional property called hobbies, which is an array of strings. You can manipulate these nested arrays in the same way you would manipulate any array.

Conclusion

Working with arrays of objects in TypeScript is a powerful way to handle complex data structures, enabling you to store, manipulate, and retrieve information efficiently.

Get Mayur Koshti’s stories in your inbox

Join Medium for free to get updates from this writer.

By leveraging TypeScript’s static typing and features like type aliases, you can write clean, maintainable, and bug-resistant code.

Whether you are building a list of users, products, or any other data-driven application, arrays of objects are a common and useful data structure.

As we’ve seen through the examples, TypeScript provides strong type-checking, which helps to catch errors early and ensures a smoother development process.

Start practicing these concepts in your projects, and you’ll quickly see how useful and flexible arrays of objects can be!

Thank you for reading until the end. Before you go:

Be sure to clap and follow the writer ️👏️️

Follow me: https://medium.com/@mayurkoshti12

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--

Mayur Koshti
Mayur Koshti

Written by Mayur Koshti

Dynamic Programmer. I like to write on coding solution and latest tech-related information. My aim is to provide the best knowledge in easy way.

Stackademic
Stackademic

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.