What is preventing obj from being iterable?

When I try to compile this code, an error appears stating that the object is not iterable. Why is this happening? My goal is to determine the number of users currently online.

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  let num =0;
  for(let user of obj){
    if(user['online']==true){
      num++;
    }
  }
  return num;
}

console.log(countOnline(users));

Answer №1

Instead of utilizing the for...of method, you are advised to use for...in.

for...of is specifically designed for iterating over iterable objects, whereas for...in is used to loop through the enumerable properties of an object. To make for...of function correctly, the object must support the @@iterator method (such as Array, string, Set, etc)

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  let num = 0;
  for (let user in obj) {
    if (obj[user]['online'] == true) {
      num++;
    }
  }
  return num;
}

console.log(countOnline(users));

When using for...in, the variable user will represent the key of the object like Alan. Therefore, to access the value of a property, you need to use obj[user] (e.g., obj["Alan"]). The condition should be adjusted accordingly:

if (obj[user]['online'] == true)

Answer №2

By default, objects do not come with the @@iterator symbol. To utilize the for..of loop, you must add it to the object:

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

users[Symbol.iterator] = function*() {
  for (value of Object.values(this)) {
    yield value;
  }
};

for (let user of users) {
  console.log(user)
}

Alternatively, you can also use for..of in combination with Object.entries (or Object.values)

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

for (let [key, value] of Object.entries(users)) {
  console.log('key :', key, 'value : ', value)
}

console.log('***********');

for (let user of Object.values(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

What is the process for importing from vueuse into Vue SFC Playground?

After attempting to integrate vueuse through an Import Map using the code @vueuse/core": "https://www.unpkg.com/@vueuse/core?module, I encountered an issue where reactivity was not functioning as expected in vueuse. The import process appeared t ...

The issue with Node.js arises when attempting to access data within a nested fs.readFile call

This is my initial attempt at a nodejs project and I'm struggling to pinpoint the issue: https://i.sstatic.net/NsI7M.png fs.readFile("/home/shaurya/Desktop/test.txt","utf-8", function(err,filedata1){ fs.readFile(filedata1,"utf-8",function(err, ...

What is the best way to sort through received JSON information?

I am attempting to create a simple command that retrieves information from imgur, locates the images, and then randomly selects which photo to display. The issue I am encountering is my inability to filter the responses based on specific criteria. Below is ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

Shifting a division using insertAfter

Hey there! I'm having a bit of trouble using the insertAfter function. In each product in my store, I need to position an "add to cart" button after the price. This is the code I tried: <Script type="text/javascript" > jQuery(document).read ...

Angular table elements can trigger a click event that redirects to a unique URL generated from the ID of the selected element

In the angular table, every element should be clickable. When any element in the table is clicked, it should use its ID to perform a new search and redirect to the URL based on that ID of the clicked element. Below is the JSON data from the initial URL. It ...

When a directive generates an element, the ng-click function may not function as expected

I am developing a custom directive using angularJS. The directive is supposed to replace my custom element with pagination elements. However, the generated elements by the directive contain an ng-click attribute whose value is a function from the controlle ...

Retrieve data from MongoDB using the unique identifier (_id) and additional conditions with Express

Below is the code I am currently working with: PostCategory.find({categoryid:category._id.str},function(err,postcategories){ if(err) return next(err); Post.find({_id:postcategories.postid},function(err,posts){ if(err) ...

Can Google Maps be initialized asynchronously without the need for a global callback function?

Currently, I am working on developing a reusable drop-in Module that can load Google Maps asynchronously and return a promise. If you want to take a look at the code I have constructed for this using AngularJS, you can find it here. One issue I have enco ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

Using class objects in list comprehensions

In my subfile.py, I have defined a class called StrucData: class StrucData: def __init__(self, name): self.name = name def loadData(self, size=1, cost=1): self.size = size self.cost = cost When working in the main file, I: Invoke the sub ...

What is the best way to switch between search results shown in an li using AngularJS?

Looking for a way to toggle a list that appears when a user searches in my app. I want the search results to hide when the search bar is closed. How can I achieve this? I think Angular might be the solution, but I'm stuck on how to implement it. I tri ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

Confirming user banking information is necessary solely for account activation through Stripe

I've been working with NodeJS and ExpressJS Is there a way to set up account verification with Stripe? I want to confirm that users have bank accounts without charging them. What kind of information can I access through this verification process? My ...

Headers have already been sent to the client and cannot be reset

Although I am relatively new to using nodeJs, I have conducted research to troubleshoot my issue. However, it appears that I am struggling a bit with asynchronous functionalities. I came across a solution that unfortunately did not work as expected. Here i ...

Efficiently flattening an array in JavaScript using recursive functions without the need for loops

Currently I am studying recursion and attempting to flatten an array without using loops (only recursion). Initially, I tried the iterative approach which was successful, but I am facing challenges with the pure recursive version: function flattenRecurs ...

Using Three.js to apply multiple images onto a sphere and have individual control over each one

I have a 3D sphere that I am looking to map an array of images onto. I want to be able to control each image independently, allowing for fading in and out of each image. To better illustrate my goal, I will provide an example image of what I am trying to a ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

What is the best way to display two radio buttons side by side in HTML?

Looking at my HTML form in this JSFiddle link, you'll see that when the PROCESS button is clicked, a form with two radio buttons appears. Currently, they are displayed vertically, with the female radio button appearing below the male radio button. I& ...

Execute a post request upon clicking with NEXT JS, while also firing off a get request

I'm facing an issue where I need to post and get my data when clicking on the same button (similar to writing and displaying comments). However, whenever I click the button, everything seems to be working fine but a request with a 304 status code star ...