How to Iterate Over Objects in TypeScript?

Recently, while working on a TypeScript form, I needed to go through form fields that had different keys each time. The form wasn’t fixed, so I needed a flexible way to handle the data, but I still wanted to use TypeScript’s type safety.

In this short tutorial, I’ll show you how to use Object.entries() to iterate over objects in TypeScript. We’ll use a simple example with form fields like username, email, and age to make it easy to understand.

Why Iterate Over Objects in TypeScript?

Iterating over objects is a common task in programming, especially when you need to access or manipulate data dynamically. Whether you’re building a web application, a server-side application, or handling data from an API, understanding how to iterate over objects can save you time and effort.

TypeScript, being a superset of JavaScript, provides several ways to iterate over object properties. These methods not only help in accessing the data but also in ensuring type safety, which is one of the primary benefits of using TypeScript.

Check out: Create an Object from an Interface in TypeScript

Methods to Iterate Over Objects in TypeScript

1. for…in Loop

The for…in loop is a straightforward way to iterate over the keys of an object. This loop iterates over all enumerable properties of an object that are keyed by strings.

Example:

interface Person {
    firstName: string;
    lastName: string;
    age: number;
}

const person: Person = {
    firstName: "John",
    lastName: "Doe",
    age: 30
};

for (const key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(`${key}: ${person[key as keyof Person]}`);
    }
}

Output:

Object Iteration in Typescript

In this example, we have an object person with properties firstName, lastName, and age. The for…in loop iterates over these properties and logs them to the console.

Check out: for…in Loops in TypeScript

2. Object.keys()

The Object.keys() method returns an array of a given object’s own enumerable property names. This method is useful when you need to work with the keys directly.

Example:

const person = {
    firstName: "Jane",
    lastName: "Smith",
    age: 25
};

Object.keys(person).forEach(key => {
    console.log(`${key}: ${person[key as keyof typeof person]}`);
});

Output:

Tpescript object iteration using keys

Here, Object.keys(person) returns an array of keys, which we then iterate over using forEach.

3. Object.values()

The Object.values() method returns an array of a given object’s own enumerable property values. This is useful when you only need the values and not the keys.

Example:

const person = {
    firstName: "Alice",
    lastName: "Johnson",
    age: 28
};

Object.values(person).forEach(value => {
    console.log(value);
});

Output:

Iterate Over Objects in TypeScript

In this example, Object.values(person) returns an array of values, which we iterate over using forEach.

Check out: Do-While Loop in TypeScript

4. Object.entries()

The Object.entries() method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs. This method is beneficial when you need both keys and values.

Example:

const person = {
    firstName: "Michael",
    lastName: "Brown",
    age: 35
};

Object.entries(person).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

Output:

Iterate Object array in Typescript

Here, Object.entries(person) returns an array of key-value pairs, which we iterate over using forEach.

5. Using Map and Set

While Map and Set are not objects in the traditional sense, they are collections that can store key-value pairs and unique values, respectively. They provide methods that make iteration straightforward.

Example with Map:

const personMap = new Map<string, string | number>([
    ["firstName", "David"],
    ["lastName", "Williams"],
    ["age", 40]
]);

personMap.forEach((value, key) => {
    console.log(`${key}: ${value}`);
});

Output:

Iterate object in typescript using Map

Example with Set:

const personSet = new Set<string>(["David", "Williams", "40"]);

personSet.forEach(value => {
    console.log(value);
});

Output:

Iterate Over Objects in TypeScript using set

Check out: Break Statement in TypeScript For Loops

Practical Use Cases to Iterate Objects in TypeScript

Handling API Responses

Often, when working with APIs, you receive data in the form of objects. Iterating over these objects allows you to manipulate the data as required.

Example:

interface ApiResponse {
    id: number;
    name: string;
    email: string;
}

const response: ApiResponse = {
    id: 1,
    name: "Emily Clark",
    email: "emily.clark@example.com"
};

for (const key in response) {
    if (response.hasOwnProperty(key)) {
        console.log(`${key}: ${response[key as keyof ApiResponse]}`);
    }
}

Output:

Iterate Objects in TypeScript to handle API

Dynamic Form Handling

When building forms dynamically, you might need to iterate over form data to validate or process it.

Example:

interface MyFormData {
    [key: string]: string | number;
}

const formData: MyFormData = {
    username: "john_doe",
    email: "john.doe@example.com",
    age: 30
};

Object.entries(formData).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

Output:

Object Iteration in Typescript form data

Check out: Use for…of Loops in TypeScript

Configuration Settings

Iterating over configuration settings stored in objects can help in applying them dynamically.

Example:

interface Config {
    apiUrl: string;
    retryAttempts: number;
    timeout: number;
}

const config: Config = {
    apiUrl: "https://api.example.com",
    retryAttempts: 3,
    timeout: 5000
};

Object.keys(config).forEach(key => {
    console.log(`${key}: ${config[key as keyof Config]}`);
});

Conclusion

In this tutorial, we learned how to iterate over objects in TypeScript using the Object.entries() method. This is especially useful when working with dynamic data, such as form fields that don’t have fixed keys.

By defining an interface like MyFormData, we can safely access both keys and values while keeping TypeScript’s type safety. Whether you’re handling form submissions, API responses, or configuration objects, this method helps you write clean and reliable code.

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.