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
>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)
}