TypeScript for ... of with index / key?

Cover Image for TypeScript for ... of with index / key?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

TypeScript for ... of with index / key? 🤔

So you're getting your hands dirty with TypeScript and you stumble upon the for...of loop. It seems simple and straightforward, but you quickly realize that it lacks the ability to access the index or key of each iterated item. 😩

Fear not, my fellow TypeScript adventurer! In this guide, we'll explore some common issues and provide easy solutions to add an index or key to your for...of loop. Let's dive in! 💪

The Problem 😱

As you've noticed, the basic for...of loop in TypeScript only gives you access to the item itself, but not its index or key. This can be frustrating when you need to work with both the item and its position in an array or the key in an object.

The Solution 🎉

To overcome this limitation, TypeScript provides a convenient way to iterate over arrays or objects while also accessing their indices or keys. Let's see how it works!

Iterating over Arrays 🌈

To iterate over an array and access both the item and its index, we can use the entries() method of the Array object. Here's an example:

const someArray = [9, 2, 5];
for (const [index, item] of someArray.entries()) {
    console.log(`Index: ${index}, Item: ${item}`);
}
// Output: Index: 0, Item: 9
//         Index: 1, Item: 2
//         Index: 2, Item: 5

By using someArray.entries(), we get an iterator that returns an array of [index, item] pairs. We can then use destructuring assignment to conveniently access both the index and the item in each iteration.

Iterating over Objects 🌟

If you're working with objects and need to iterate over their keys, TypeScript has you covered as well. We can use the Object.entries() method to achieve this. Let's take a look:

const someObject = { apple: 3, banana: 1, cherry: 2 };
for (const [key, value] of Object.entries(someObject)) {
    console.log(`Key: ${key}, Value: ${value}`);
}
// Output: Key: apple, Value: 3
//         Key: banana, Value: 1
//         Key: cherry, Value: 2

By using Object.entries(someObject), we transform the object into an iterable array of [key, value] pairs. Again, with destructuring assignment, we can easily access both the key and the value in each iteration.

Ready to Enhance Your for...of Loop? 🚀

Now that you know how to add an index or key to your for...of loop, go ahead and level up your TypeScript skills! Use these techniques whenever you need to work with the position or key of each item in your arrays or objects.

If you have any questions or other cool TypeScript tips to share, feel free to leave a comment below. Let's keep the TypeScript community thriving and code happily ever after! 👩‍💻👨‍💻

Happy coding! 😄


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello