How to get through the Node.js array

How can I display array variables?

the code:

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

Exit:

 { rooms: [ { room: 'Raum 1', persons: 1 }, { room: 'R2', persons: 2 }, { room: 'R3', persons: 3 } ] } rooms 
+8
source share
3 answers

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

 for(let val of rooms) { console.log(val) } 
+24
source
 for (var i in rooms) { console.log(rooms[i]); } 

Note that it is recommended that you check hasOwnProperty with in and this applies to objects. So you are better off with for...of or for forEach .

+4
source

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

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

Using For with your code example (if we want to return the rooms) looks like this:

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

Note: the noticeable difference between For for and forEach is For of break break and forEach does not have the ability to break to stop the loop (without throwing an error).

+3
source

Source: https://habr.com/ru/post/1014127/


All Articles