The for...of loop cannot be used with the .for property since it is not iterable. (Is

let arr = [{
    category: 'music',
    views: 20
  },
  {
    category: 'abc',
    views: 32
  },
  {

    category: 'bob',
    views: 20
  }
]

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

console.log(Array.isArray(arr))

Error: .for is not iterable

Array.isArray(arr) returns true

Why is the array not iterable?

Is it necessary to use this method to retrieve the index of each item?

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

Nevermind ...it works well with forEach

arr.forEach((key, value) => {
    console.log(key,value)
})

What's happening with for...of here?

Note: Using for...in is not an option because the order needs to be guaranteed

Answer №1

for..of loops through only values, not keys and values.
To iterate through both array indices and values, use Array::entries().
Alternatively, if you only need properties in your array items, object destructuring can be used:

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

    name: 'bob',
    views: 20
    }   
]

// possibly what was intended
for (const [k, v] of collection.entries()){
    console.log(k, v)
}

// for accessing item properties
for (const {name, views} of collection){
    console.log(name, views)
}

UPDATE
Keep in mind that utilizing an iterator like Array::entries() is the slowest method to iterate a large array (a custom generator function yields the same outcome). Based on my testing in Chrome with an array of 10000000 items, it is 1.5-2x slower than Array::forEach() and for..of (which are essentially identical in implementation), and at least 6x slower than the classic

for(let i = 0; i < arr.length; i++)

approach, which remains the fastest way to loop through an array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Carrying over additions in arrays using only Javascript

I'd like to implement a basic array addition with carryover. Additionally, I need to display the carryover and result values. For instance: e.g var input = [[0,0,9],[0,9,9]]; var carryover = []; var result = []; Thank you! ...

Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up. Do you think this is achievable? Although I have succeeded in wrapping it while ...

What is the best way to incorporate new elements into the DOM in order to allow users to share their comments

Can anyone help me with the code below? I have a text box and a comment section, along with a button to add comments. However, I need assistance with adding the posted comment below the comment section. Below is the code snippet: <div id="comments"&g ...

Set the current time to ISO8601 format

I need assistance with creating a "time passed" counter for my website based on an API call that returns data in the following format: "created_at": "2018-05-16T14:00:00Z", What is the best approach to calculate and display the time that has passed since ...

Avoiding the sudden appearance of unstyled content in Single-File Components

I am looking to update my HTML navigation <div id="header-wrapper"> <div id="header-logo-title"> <nav> <ul id='mainNav'> <li>Home</li> </ul> </nav> ...

What is the best way to ensure type safety in a Promise using Typescript?

It seems that Promises in Typescript can be type-unsafe. This simple example demonstrates that the resolve function accepts undefined, while Promise.then infers the argument to be non-undefined: function f() { return new Promise<number>((resolve) ...

Using nightwatch.js to verify elements across different parts of a webpage

Currently engaged in working with nightwatch.js and encountering an issue with a particular page file structure: sections: { table: { selector: '.sr-filterable-data-layout--collection', elements: { header: { ...

Intermittent connectivity issues causing clients to miss messages from Nodejs server

Currently, I am in the process of setting up a basic node application where visitors can interact with a letter counter on the site. The idea is that every time someone presses a letter, the counter will increase and all users will be able to see it go up ...

What is the best way to execute individual API requests for various sheets within the same spreadsheet?

I am currently working on integrating the Google Sheets API with Node.js. I need assistance with understanding the correct syntax for calling two separate sheets within one spreadsheet. After reaching out to chatgpt and gemini, I received conflicting answe ...

Insert a new class within the container div

I am looking to insert a 'disabled' class within a parent div named 'anchorxx' https://i.sstatic.net/3KRMQ.png The disabled class div can be located anywhere within the anchorXX divs Is it achievable using jquery? I am unsure how to ...

What is the best way to navigate a carousel containing images or divs using arrow keys while maintaining focus?

Recently, I have been exploring the Ant Carousel component which can be found at https://ant.design/components/carousel/. The Carousel is enclosed within a Modal and contains multiple child div elements. Initially, the arrow keys for navigation do not work ...

What is the best way to halt a jQuery function when hovering over it?

Currently, I have a jQuery function set up to run on setInterval(). However, I am looking for a way to pause the interval when hovering over the displayed div and then resume once no longer hovering (i.e., continue cycling through the divs). Does anyone ...

Is it true that DOM objects in JavaScript are considered objects?

I've been searching for an official answer to this question, but it seems there is some confusion. Some people consider DOM objects to be JS objects, while others argue that they are different entities. What is the correct answer? If you search on Sta ...

When the user presses either the refresh button or the back button, they will be redirected

After the user presses refresh or uses the browser back button, I need to redirect them to a specific page in order to restart the application. My JavaScript code is as follows: var workIsDone = false; window.onbeforeunload = confirmBrowseAway; function ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

Looking for an API to retrieve random quotes and images from a website?

Greetings, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS along with the basics of JS. Level of Expertise: Beginner During my exploration, I stumbled upon this intriguing website - . It stands out a ...

Troubleshoot: Node Express experiencing issues reconnecting to ajax

Here is the initial question that needs to be addressed. I am currently developing an API that links a front-end application (built using node, express, and Ajax) with a Python swagger API. The issue I am facing is that although I can successfully send da ...

Customize your Material-UI theme with a unique hover effect for contained buttons

Currently, I am in the process of setting up a theme for Material-Ui on my React application. Within the app, there are two types of buttons that I utilize - contained and outlined. The issue lies with the hover effect on the contained button (while the ou ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

Utilizing the outcome of an AJAX call in JavaScript

I am facing an issue with a query that is returning 2 rows. Below is my PHP code snippet: $arr = array(); $stmt = $dbh_conn->prepare("SELECT id,name FROM mytable WHERE id <= 2"); $stmt->execute(); $result = $stmt->fetchAll(); /*Array ( ...