Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

for…of .for is not iterable (on an array???)

let collection = [{
    name: 'music',
    views: 20
  },
  {
    name: 'abc',
    views: 32
  },
  {

    name: 'bob',
    views: 20
  }
]

for (const [k, v] of collection) {
  console.log(k, v)
}

console.log(Array.isArray(collection))

Error: .for is not iterable

Array.isArray(collection) returns true

How can an array not be iterable?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Do I really need to resort to this to "get" the index of each item?

for (let i = 0; i < collection.length; i++){
    console.log(i, collection[i])
        
}

nvm …it works fine with forEach

collection.forEach((k, v) => {
    console.log(k,v)
})

What’s going with for…of here?

Note: I can’t use for…in b/c i need the order to be guaranteed

>Solution :

for..of iterates only values, not keys and values.
Use Array::entries() to iterate both array indices and values.
On the other hand if you need only properties in your array’s items you can use object destructuring:

let collection = [
    {
    name: 'music',
    views: 20
    },
    {
    name: 'abc',
    views: 32
    },
    {

    name: 'bob',
    views: 20
    }   
]

// probably what you wanted
for (const [k, v] of collection.entries()){
    console.log(k, v)
}

// if you need items' properties
for (const {name, views} of collection){
    console.log(name, views)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading