How to use for…of loop with an Object in JavaScript

In my last post, I discussed Always Use the for…of loop to iterate in JavaScript. After this post, I got a question that, is it possible to use for…of loop with an object?

Means, can you use the for…of loop to iterates properties of an object.  Let us try this,


let Product = {
    Id: 1,
    Title: 'Pen',
    Price: 1000,
    sendDetail: () => { }
}
 
for (let p of Product) {
    console.log(p);
}

As you see, JavaScript throws you a TypeError, Product is not iterable. And this is expected, as for…of loop only iterates over the set of values produced over an iterator and an object literal is not iterable.

But you can make an object iterable using the Symbols.  


let Product = {
    Id: 1,
    Title: 'Pen',
    Price: 1000,
    sendDetail: () => { },
    [Symbol.iterator]: function* () {
        for (i in this) {
            yield [i, this[i]];
        }
    }
}

In the Product object, a new generator function is added. We will cover generators in details on another post, but putting it simply,

When you call a generator, it does not execute its body immediately, instead it returns an iterator object.

The symbol is a new type in JavaScript, and a Symbol function exposes members of built-in objects.

So, combining these two, we are exposing properties as an iterable object using the generator function.

At this point, you can use for…of loop with the Product object,


for (let p of Product) {
    console.log(p);
}

You get the output as below,

You can remove methods of object from becoming iterable by modifying the generator as shown below,


let Product = {
    Id: 1,
    Title: 'Pen',
    Price: 1000,
    sendDetail: () => { },
    [Symbol.iterator]: function* () {
        for (i in this) {
            if (typeof this[i] !== "function") {
                yield [i, this[i]];
            }
        }
 
    }
}
 
for (let p of Product) {
    console.log(p);
}

Now you should get the output as below,

In this way, by using a generator function and Symbols, you can make an object iterable and can then use with the for…of loop. I hope you find this post useful. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s