Search code examples
javascriptfor-of-loop

Javascript - for-of loop crashing when trying to loop through an object


I have this object passed in by a function

enter image description here

and then I want to loop through it with this code

    let formData = new FormData();
    let item = {};
    let i = 0;
    for (item of files) {
        formData.append('file' + i, files[i]);
        formData.append('filesNumber', i + 1);
        i++;
    }

but when the execution reaches the declaration of the for loop, it crashes with this error

Uncaught TypeError: files[Symbol.iterator] is not a function

What is wrong?


Solution

  • Basic objects do not automatically implement Symbol.iterator. Here's a list of objects that do.

    In order to use the for..of syntax, you'll have to implement your own iterator.

    let files = {
      0: "a",
      1: "b",
      2: "c",
      
      [Symbol.iterator]: function*() {
        let i = 0;
        while (this.hasOwnProperty(i)) {
          yield this[i];
          i++;
        }
      }
    };
    
    for (let item of files) {
      console.log(item);
    }

    Alternatively, you just grabs the objects keys and iterate over them.

    let files = {
      0: "a",
      1: "b",
      2: "c"
    };
    
    let keys = Object.keys(files);
    for (let i = 0; i < keys.length; i++) {
      let key = keys[i];
      let item = files[key];
      console.log(`${key}: ${item}`);
    }

    You can also use the good, old-fashioned for..in loop to go over the keys.

    let files = {
      0: "a",
      1: "b",
      2: "c"
    };
    
    for (let key in files) {
      console.log(`${key}: ${files[key]}`);
    }