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
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.
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.
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.
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) }
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With