How to Work with Arrays of Objects in TypeScript?

In this tutorial, I will explain how to define, create, and manipulate arrays of objects in TypeScript. Arrays of objects are helpful for storing and working with collections of structured data in your TypeScript programs. I will explain here how to use arrays of objects in TypeScript properly.

What is an Array of Objects in TypeScript?

An array of objects in TypeScript is a collection of objects that are stored in an array data structure. Each object in the array typically has the same structure or schema, defined by an interface or type in TypeScript.

For example, let’s say we have an application that needs to store information about US states. We could define an interface called State to represent the structure of each state object:

interface State {
  name: string;
  capital: string;
  population: number;
}

We can then create an array of State objects like this:

const states: State[] = [
  { name: 'California', capital: 'Sacramento', population: 39538223 },
  { name: 'Texas', capital: 'Austin', population: 29145505 },
  { name: 'Florida', capital: 'Tallahassee', population: 21538187 },
  // ... more state objects
];

As you can see, each object in the states array conforms to the structure defined by the State interface, with a name, capital, and population property.

Check out How to Filter Arrays in TypeScript?

Define an Array of Objects in TypeScript

To define an array of objects in TypeScript, we first need to define the structure of the objects using an interface or type.

As shown in the previous example, we can define an interface for our State objects:

interface State {
  name: string;
  capital: string; 
  population: number;
}

Then, to actually create an array of State objects, we use the Array type or the shorthand T[] syntax, where T is the type of the objects in the array, in this case State:

const states: Array<State> = []; // or
const states: State[] = [];  

Both of these are equivalent ways to define an array of State objects in TypeScript.

Add Objects to an Array in TypeScript

Once we have an array of objects defined, we can add objects to it in a few different ways.

One way is to simply initialize the array with objects directly:

const states: State[] = [
  { name: 'New York', capital: 'Albany', population: 20201249 }, 
  { name: 'Pennsylvania', capital: 'Harrisburg', population: 13002700 },
  { name: 'Illinois', capital: 'Springfield', population: 12812508 },
];

We can also add objects to an existing array using the push() method:

const newState: State = { name: 'Ohio', capital: 'Columbus', population: 11799448 };
states.push(newState);

Or we can use the spread operator (…) to concatenate a new object to the end of the array:

states = [...states, { name: 'Georgia', capital: 'Atlanta', population: 10711908 }];

All of these methods allow us to add new objects that match the State interface to our states array.

Read How to Filter an Array of Objects in TypeScript?

Access Objects in an Array in TypeScript

Once we have objects in our array, we need ways to access and work with those objects.

We can access individual objects by their index in the array:

const california = states[0];
console.log(california.name); // "California"

To access a property on an object, we use dot notation, like california.name to get the name property.

We can also loop over all the objects in the array using various methods like for…of, forEach(), map(), etc.

For example, to log the name of each state to the console:

for (const state of states) {
  console.log(state.name);
}

This will print:

"California" 
"Texas"
"Florida"
"New York"
"Pennsylvania" 
"Illinois"
"Ohio"  
"Georgia"

Read How to Sort an Array of Objects by Property Value in TypeScript?

Manipulate Objects in an Array in TypeScript

In addition to accessing objects, we often need to update or manipulate the objects in our array.

To update an object, we can access it by index and then modify its properties directly:

states[0].population = 39237836;
console.log(states[0].population); // 39237836

We can also use methods like map() to transform the objects in the array and return a new array:

const stateNames = states.map(state => state.name);
console.log(stateNames); // ["California", "Texas", "Florida", ...]

This creates a new array stateNames containing only the name of each state, extracted from the State objects in the states array.

We can even use filter() to return a new array containing only objects that match a certain criteria:

const bigStates = states.filter(state => state.population > 20000000);
console.log(bigStates); // [{ name: "California", ... }, { name: "Texas", ... }]

Now, bigStates is a new array containing only the state objects that have a population greater than 20,000,000.

Sort Objects in an Array in TypeScript

Another common task with arrays of objects is sorting them based on one or more properties.

To sort the states array by population in ascending order:

states.sort((a, b) => a.population - b.population);

And to sort by name in alphabetical order:

states.sort((a, b) => a.name.localeCompare(b.name));

The sort() method takes a comparison function that determines the order of the objects based on their properties.

Immutability and Arrays of Objects

Immutability is one thing to remember when working with arrays of objects in TypeScript. In general, it’s a good practice to treat arrays and objects as immutable, meaning we don’t modify them directly, but instead create new arrays or objects with the updated values.

For example, instead of modifying the population directly like we did earlier:

// Avoid this:
states[0].population = 39237836;

It’s better to create a new object with the updated value:

const updatedState = { ...states[0], population: 39237836 };
const updatedStates = [updatedState, ...states.slice(1)];

This creates a new object updatedState with the population property updated, and then a new array updatedStates with the first object replaced by updatedState, and the rest of the objects from the original states array.

By treating objects and arrays as immutable, we can avoid unintended side effects and make our code more predictable and easier to reason about.

Conclusion

Arrays of objects are a fundamental data structure in TypeScript that allows us to work with collections of structured data in a type-safe and efficient way. In this tutorial, I explained how to define interfaces for our objects, create arrays of those objects, and manipulate them with various array methods in TypeScript.

You may also like: