Languages
[Edit]
EN

TypeScript - iterate over object

0 points
Created by:
a_horse
478

In this article, we would like to show you how to iterate over an object in TypeScript.

Below examples show two ways of how to do that:

  1. Using for...in statement
  2. using Object.entries() method

1. for...in statement example

The below example shows how to iterate over object properties using for...in statement.

Practical example:

interface MyObject {
  a: number;
  b: number;
  c: number;
}

const object: MyObject = { a: 1, b: 2, c: 3 };

for (const prop in object) {
  console.log(prop);
}

Output:

a
b
c

2. Object.entries() method example

The below example shows how to iterate over object using Object.entries() to get every key / value pair from object.

interface MyObject {
  a: number;
  b: number;
  c: number;
}

const object: MyObject = { a: 1, b: 2, c: 3 };

for (const [key, value] of Object.entries(object)) {
  console.log(`${key}: ${value}`);
}

Output:

a: 1
b: 2
c: 3

Alternative titles

  1. TypeScript - loop through object
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join