uneasy
uneasy

Reputation: 619

JavaScript: why [object Array] is not iterable with for( i of array)

I am having weird issue. I wanted to replace for (let i=0;i<arr.length;i++) with for( const[key,val] of arr) but I am getting error .for is not iterable

When I check my array with Object.prototype.toString.call(arr) i get [object Array] I am not insisting on using that form, but just want to understand why is this happening: my array looks like (array of objects):

[
  {
    fieldname: 'files',
    originalname: 'User Manual 3.0.pdf',
    encoding: '7bit',
    mimetype: 'application/pdf',
    buffer: <Buffer 25 50 44 46 2d 31 2e 37 0d 0a 25 b5 b5 b5 b5 0d 688657 more bytes>,
    size: 688707
  }
]

Upvotes: 2

Views: 13735

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

for( const[key,val] of arr) is trying to use

  1. An iterator for arr (the for-of part), which is fine; and

  2. An iterator for each value produced by #1 (the [key, val] part), which isn't fine because those are non-iterable objects

If you want to loop through the properties of the objects in arr in key, value form, you'll need Object.entries:

for (const entry of arr) {
    for (const [key, value] of Object.entries(entry)) {
        // ...
    }
}

(Or for-in if you want to include inherited properties.)

Live Example:

const arr = [
  {
    fieldname: 'files',
    originalname: 'User Manual 3.0.pdf',
    encoding: '7bit',
    mimetype: 'application/pdf',
    /*
    buffer: <Buffer 25 50 44 46 2d 31 2e 37 0d 0a 25 b5 b5 b5 b5 0d 688657 more bytes>,
    */
    size: 688707
  }
];

for (const entry of arr) {
    for (const [key, value] of Object.entries(entry)) {
        console.log(key, value);
    }
}

If you only wanted specific properties from the objects in arr, you could use object destructuring rather than iterable destructuring:

for (const {fieldname, originalname} of arr) {
    console.log(`fieldname = ${fieldname}, originalname = ${originalname}`);
}

Live Example:

const arr = [
  {
    fieldname: 'files',
    originalname: 'User Manual 3.0.pdf',
    encoding: '7bit',
    mimetype: 'application/pdf',
    /*
    buffer: <Buffer 25 50 44 46 2d 31 2e 37 0d 0a 25 b5 b5 b5 b5 0d 688657 more bytes>,
    */
    size: 688707
  }
];

for (const {fieldname, originalname} of arr) {
    console.log(`fieldname = ${fieldname}, originalname = ${originalname}`);
}

Upvotes: 4

Paul George
Paul George

Reputation: 1

You cannot directly access the JSON key value pair by iterating the array. As T.J mentioned, you need to iterate the array and then iterate the key values from the object.

Upvotes: -1

Related Questions