Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Javascript object become iterable with for...of statement? [duplicate]

I would like to set the options[Symbol.iterator] property in order to iterate on the simple objects I create with the for...of statement :

options = {
  male: 'John',
  female: 'Gina',
  rel: 'Love'
};


for(let p of options){
  console.log(`Property ${p}`);
};

But this code gives me the following error:

 array.html:72 Uncaught TypeError: options[Symbol.iterator] is not a function

How I can set the right iterator function on a simple object as above?

Solved

 // define the Iterator for the options object 
 options[Symbol.iterator] = function(){

     // get the properties of the object 
     let properties = Object.keys(this);
     let count = 0;
     // set to true when the loop is done 
     isDone = false;

     // define the next method, need for iterator 
     let next = () => {
        // control on last property reach 
        if(count >= properties.length){
           isDone = true;
        }
        return {done:isDone, value: this[properties[count++]]};
     }

     // return the next method used to iterate 
     return {next};
  };

And I can use the for...of statement on my object now iterable :

 for(let property of options){
   console.log(`Properties -> ${property}`);
 }
like image 887
cicciosgamino Avatar asked Mar 05 '16 20:03

cicciosgamino


People also ask

How do you make an object iterable in JavaScript?

To make the range object iterable (and thus let for..of work) we need to add a method to the object named Symbol. iterator (a special built-in symbol just for that). When for..of starts, it calls that method once (or errors if not found). The method must return an iterator – an object with the method next .

Can we use a object in for..of loop?

The for...of loop cannot be used to iterate over an object. You can use for...in to iterate over an iterable such arrays and strings but you should avoid using for...in for iterables. The for...of loop was introduced in ES6.

Can we use for..of loop for object in JavaScript?

Introduction to looping through objects using javascript If you have an array that is considered to be an object in javascript, you can't loop through the array using map(), forEach(), or a for..of loop.

What is for..of loop in JavaScript?

The For Of Loop The JavaScript for of statement loops through the values of an iterable object.


1 Answers

To use for...of loop you should define an appropriate iterator for your object using [Symbol.iterator] key.

Here is one possible implementation:

let options = {
  male: 'John',
  female: 'Gina',
  rel: 'Love',
  [Symbol.iterator]: function * () {
    for (let key in this) {
      yield [key, this[key]] // yield [key, value] pair
    }
  }
}

Though, in most cases it'll be better to iterate over objects using plain for...in loop instead.

Alternatively you could convert your object to iterable array using Object.keys, Object.values or Object.entries (ES7).

like image 173
Leonid Beschastny Avatar answered Sep 18 '22 15:09

Leonid Beschastny