Reputation: 1291
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
Upvotes: 46
Views: 136164
Reputation: 66455
for (const i in rooms) {
console.log(rooms[i]);
}
Note it's good practice to do a hasOwnProperty
check with in
and it is for objects. So you're better off with for...of
or forEach
.
Upvotes: 8
Reputation: 28339
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)
}
Upvotes: 85
Reputation: 3420
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).
Upvotes: 15