Issue with logging objects in an array within a for loop

I am having an issue with a JavaScript for-in loop.

Why does console.log(user) display the number "0" when iterating through users?

Is it indicating the index of the user object in the array?

I would like to log each object individually...

Thank you

router.post("/api/verification/check", auth, async (req, res) => {
    try {
      const users = await User.find({ /* retrieve users */ })

      console.log(`${users}`)           // displays user object
      
      for (const user in users) {
        console.log(user)               // shows "0" ???
   
      }

    } catch (err) {
      res.status(400).send()
    }
  }
)

Answer №1

When using the for-in loop, you will receive the index of the array rather than the value itself. To access the value, you will need to look it up using the index.

for (const i in users) {
   console.log(users[i]);
}

[update] Alternatively, you can opt for the for-of loop.

for (const user of users) {
   console.log(user);
}

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

Tips for developing a nested array of objects using a JavaScript loop

Can someone help me with looping an AJAX response to create an array in this format? "2023-03-30": {"number": '', "url": ""}, "2023-03-30": {"number": '', "url": &quo ...

What happens to the npm package if I transfer ownership of a github repository to a different user?

I was considering transferring a GitHub repository to another user or organization, but I have concerns about what will happen to older versions of the npm package associated with it. Let's say my Node.js package is named node-awesome-package. Versi ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

When working in React, I encountered a problem with the for of loop, as it returned an error stating "x is undefined." Although I could easily switch to using a simple for loop, I find the for of loop to

I'm encountering an issue when using a for of loop in React, as it gives me an error stating that "x is undefined". import { useEffect } from "react"; export default function HomeContent() { useEffect(() => { let content = document ...

Node.js: Issue with static file caching caused by superfluous query parameter

My Node.js code for caching static files looks like this: app.use(express.static(path.join(__dirname, "public"), { maxAge: (process.env.NODE_ENV === "local") ? 0 : 31557600000 })); The public folder contains all the necessary static files for my ser ...

Utilizing Service within Express Router

My journey into the world of NodeJS is just beginning, coming from a .NET background with a love for dependency injection, inversion of control, and microservices. I am now venturing into TypeScript to create services based on my past experiences. Using ex ...

using recursion within callback functions

In my JavaScript function with a callback, I am utilizing the "listTables" method of DynamoDB. This method returns only 100 table names initially. If there are more tables, it provides another field called "LastEvaluatedTableName", which can be used in a n ...

When the page is dynamically loaded, Ng-repeat does not function as expected

I am working on a page that includes the following code snippet: <script> angular.module('myapp', []).controller('categoryCtrl', function($scope) { $scope.category = <? echo json_encode($myarr); ?>; $scope.subcatego ...

Modifying button attribute through dropdown selection

In my project, I have a dropdown that gets its data from a database. Depending on the selection made in the dropdown, I would like to change the attribute of a button (data-uk-modal="{target:'#modal-'value of dropdown'}"). <select id "ci ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

Activate the next tab by clicking a button in ReactJS

I currently have a web page with 4 tabs, each containing different sets of data. Within the first tab, I have a button that should activate the next tab's content when clicked by the user. render(){ return ( <MuiThemeProvider> ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

Tips for handling the response after a view has been submitted on Slack using Bolt.js

Hey there! I added a simple shortcut to retrieve data from an input, but I'm facing an issue after submitting the view. The response payload is not received and the view doesn't update to give feedback to the user. Check out my code below: const ...

Error: Firebase is throwing an error stating that it cannot access the length property of an undefined property

I need help establishing a connection with Firebase. Here is the code snippet from firebase.js: import * as firebase from "firebase/compat/app"; const firebaseConfig = { apiKey: "***", authDomain: "***", projectId: &qu ...

Encountering a 400 error in Ajax following the execution of server-side validation by Express

I'm currently troubleshooting a form handler that consistently throws a 400 error post middleware validation. The middleware validation steps are as follows: const contactValidate = [ check('name') .exists() .trim() .escape() ...

What is the best way to redirect users to the login page when they are logged out from a different tab or window?

Ensuring user authentication and managing inactivity are crucial components of my Nodejs application, where I leverage cookie-session and passport.js. app.use(require("cookie-session")({ secret:keys.session.secret, resave:false, saveUninitiali ...

Guidelines on integrating Admob into Ionic framework

I tried following the steps outlined in this post: AdMob not loading ads in ionic/angular app After running the app using "ionic build ios && ionic emulate ios," I still see no ads, no black bar, nothing at all. Can someone help me figure out wha ...

Next.js pages do not respond to event listeners

Something strange is happening in my Next.js project. I've implemented a header that changes color as the page scrolls using the useEffect hook: The hook in the Header component looks like this: React.useEffect(() => { window.addEventListener(&a ...