In TypeScript, Objects are the fundamental data structures that use key-value pair structures to store the data efficiently. To iterate over them is a common task for manipulating or accessing the stored data. TypeScript is a superset of JavaScript and provides several ways to iterate over object properties. we are going to explore multiple approaches to achieve this.
These are the following approaches to Iterate Over Object Properties in TypeScript:
Table of Content
Using for...in the loop Method
This is a traditional way of iterating over the enumerable properties of objects by looping through the keys of the object, providing access to each key in the object one by one.
Syntax:
for (let key in object) { // Access object[key] here}Example: In this example, we will be using for...in the loop Method
const user = {
name : "Prateek",
age : 20,
city : "Delhi"
};
for (let key in user) {
console.log(`${key}: ${(user as any)[key]}`);
}
Output:
name: Prateek
age: 20
city: Delhi
Using Object.keys() Method (with keyof Operator)
Object. required keys() returns an array of the object's own enumerable property names called as keys. By Using keyof, we can tell the TypeScript that the keys will only be defined ones on the object, avoiding the common type errors.
Syntax:
Object.keys(object).forEach(key => {
console.log(`${key}: ${object[key]}`);
});
Example: In this example, we used assertion as Array<keyof typeof user> so that TypeScript knows that the keys are valid for the user object.
const user = { name: "Prateek", age: 20, city: "Delhi" };
(Object.keys(user) as Array<keyof typeof user>).forEach(key => {
console.log(`${key}: ${user[key]}`);
});
Output:
name: Prateek
age: 20
city: Delhi
Using Object.values() Method (for Values Only)
In some cases, we only required to iterate over values only on that case we use Objects.values() which can only retrieve the values from the object without worrying about the keys. This method returns an array of values, which we iterate easily.
Syntax:
Object.values(object).forEach(value => {
console.log(value);
});
Example: To use this you may need to change the target es lib compiler >= ES2017. Here we used Objects.values() which deals with values only. So, we don't require type assertion or handling extra type casting.
const user = { name: "Alice", age: 25, city: "New York" };
Object.values(user).forEach(value => {
console.log(value);
});
Output:
name: Prateek
age: 20
city: Delhi
Using Object.entries() Method (for Both Keys and Values)
Objects.entries() returns an array of key-value pairs as. Each value in the array has items: the key and the value. This approach is useful when we need both keys and values.
Syntax:
Object.entries(object).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Example: In this example we will be Using Object.entries() Method
const user = { name: "Alice", age: 25, city: "New York" };
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Output:
name: Prateek
age: 20
city: Delhi
Using forEach() with Object.keys() or Object.entries() Method
Using forEach() in combination with either Objects.keys() or Objects.entries() we can able to iterate over an Object effectively which is also a modern and cleaner approach.
Syntax:
Object.keys(object).forEach(key => {
console.log(`${key}: ${object[key]}`);
});
Example: Using forEach() with Object.keys() or Object.entries() gives more readable and manageable code, also by applying the keyof the safetyoperator we ensure the type saftey check for dynamic JavaScript.
interface User {
name: string;
age: number;
city: string;
}
const user: User = { name: "Prateek", age: 20, city: "Delhi" };
// Using keyof to ensure type safety
(Object.keys(user) as Array<keyof User>).forEach((key) => {
console.log(`${key}: ${user[key]}`);
});
Output:
name: Prateek
age: 20
city: Delhi