skip to Main Content
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


  1. 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)
    }
    Login or Signup to reply.
  2. 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:

    let collection = [
      { name: "music", views: 20 },
      { name: "abc", views: 32 },
      { name: "bob", views: 20 },
    ]
    
    collection.forEach((item) => {
      console.log(item.name, item.views);
    });
    
    console.log(Array.isArray(collection));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search