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?
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
2
Answers
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:
The code is attempting to use array destructuring in a for…of loop to iterate over the elements of the collection array. However, the elements of the collection array are objects, not arrays themselves, so they cannot be directly destructured in this way.
To iterate over the elements of the collection array, you can use a traditional for loop or use the forEach method of arrays. Here’s an example using forEach: