Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through Node.js array

Tags:

node.js

How can I display the variables of the array?

Code:

   console.log(rooms);    for (var i in rooms) {       console.log(i);    } 

Output:

{ rooms:         [ { room: 'Raum 1', persons: 1 },          { room: 'R2', persons: 2 },          { room: 'R3', persons: 3 } ] } rooms 
like image 414
jpsstack Avatar asked Jan 16 '17 13:01

jpsstack


People also ask

How do I loop through an array in node?

forEach() is an array function from Node. js that is used to iterate over items in a given array. Parameter: This function takes a function (which is to be executed) as a parameter. Return type: The function returns array element after iteration.

How do you iterate through an array?

Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

Can you loop through an array in JavaScript?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array.


2 Answers

For..in is used to loop through the properties of an object, it looks like you want to loop through an array, which you should use either For Of, forEach or For

for(const val of rooms) {     console.log(val) } 
like image 144
Alister Avatar answered Oct 04 '22 10:10

Alister


Using forEach() with your code example (room is an object) would look this:

temp1.rooms.forEach(function(element)  {      console.log(element)  }); 

Using For of with your code sample (if we wanted to return the rooms) looks like:

for(let val of rooms.room) {      console.log(val.room);  } 

Note: notable difference between For of and forEach, is For of supports breaking and forEach has no way to break for stop looping (without throwing an error).

like image 28
ScottyG Avatar answered Oct 04 '22 08:10

ScottyG