iterate through objects keys in typescript

You can iterate through an object's keys in TypeScript by using a for...in loop or Object.keys() method. Here is an example of both approaches:

index.ts
const myObject = { a: 1, b: 2, c: 3 };

// Using for...in loop:
for (const key in myObject) {
  if (myObject.hasOwnProperty(key)) {
    console.log(key); // Output: a, b, c
    console.log(myObject[key]); // Output: 1, 2, 3
  }
}

// Using Object.keys() method:
Object.keys(myObject).forEach(key => {
  console.log(key); // Output: a, b, c
  console.log(myObject[key]); // Output: 1, 2, 3
});
393 chars
16 lines

In the for...in loop, we check if the property is a direct property of the object using the hasOwnProperty() method. In the Object.keys() method, we use the forEach() method to iterate through the array of keys returned by Object.keys().

gistlibby LogSnag