Search code examples
javascriptjavascript-objects

Making plain objects iterable.(javascript)


So I'm working on a personal project after covering the first seven chapters of eloquent javascript by Marjin Heverbeke. Im creating school data handling system. So i already made my data structure which includes a lot of objects, so I created a test object to so that i could practice the iteration protocol, this is what i wrote

let object = {a:'a',b:'b',c:'c',d:'d',e:'e'};
object[Symbol.iterator]=function(){
    let keys = Object.keys(this);
    let count=0;
return {
    next(){
        if(count>keys.length){
            return {value: null, done:true};
        }
        else{
            let value=this[keys[count]];
            count++;
            return {value, done:false};
        }
    }
}
}

but when i do this

    for(let each of object){
       console.log([each]);
}

it outputs

//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]

I don't know what is wrong oo, pls help.


Solution

  • Try this:

    let object = {
      a: 'a',
      b: 'b',
      c: 'c',
      d: 'd',
      e: 'e',
    };
    object[Symbol.iterator] = function () {
      let keys = Object.keys(this);
      let count = 0;
      return {
        next() {
          if (count === keys.length) {
            return {
              value: null,
              done: true,
            };
          }
          let value = keys[count];
          count++;
          return {
            value,
            done: false,
          };
        },
      };
    };
    
    for (let each of object) {
      console.log([each]);
    }
    

    Note the errors were: let value=this[keys[count]]; and if (count > keys.length)