Hello Everyone, I am trying to access object inside array inside object.
I think i am not getting it right trying to access {“Number”:210, “GuestCount”:2, “Price”:100}.
Here is my full code:
var hotels = [{
"name": "Radisson",
"Address": "N Harrisson Road",
"Rooms":[
{"Number":210, "GuestCount":2, "Price":100},
{"Number":211, "GuestCount":2, "Price":110},
{"Number":212, "GuestCount":2, "Price":109}]}, {
"name": "Holiday Inn",
"Address": "S Harrison Road",
"Rooms":[
{"Number":11, "GuestCount":2, "Price":100},
{"Number":15, "GuestCount":1, "Price":58},
{"Number":22, "GuestCount":2, "Price":80},
{"Number":23, "GuestCount":2, "Price":99}]}];
/* Hotel number 1 Name and Address */
document.getElementById("radisson").innerHTML = hotels[0]["name"];
document.getElementById("first_hotel_address").innerHTML = hotels[0]["Address"];
/* Hotel Number 1 Room Information */
document.getElementById("firstHotelRoomNumber1").innerHTML = hotels["Rooms"["Number[0]"]];
/* Hotel number 2 Name and Address */
document.getElementById("holiday").innerHTML = hotels[1]["name"]; document.getElementById("second_hotel_address").innerHTML = hotels[1]["Address"];
document.getElementById("firstHotelRoomNumber1").innerHTML = hotels[0]["Rooms"][0]["Number"];
// OR this would work too:
document.getElementById("firstHotelRoomNumber1").innerHTML = hotels[0].Rooms[0].Number;
The hotels array is accessed by index, as you have done. The rooms for that first hotel are at hotels[0].Rooms orhotels[0]["Rooms"], they both mean the exact same thing. Now if you had done something like let rooms = hotels[0].Rooms; you would then simply have said rooms[0].Number or rooms[0]["Number"] – so you can string them together that same way: hotels[0].Rooms[0].Number.
Bear in mind, though – hotel is an Array of Objects, not an Object itself. And within each Hotel, there is another Array of Objects, Rooms. So it takes the combination of dot and bracket (or LOTS of brackets).
So, a suggestion. You are hard-coding all your DOM nodes, when there’s really no need. Suppose you don’t KNOW how many hotels you’ll get, or how many rooms?
Ideally, you should be able to create the hotel section dynamically. The structure is the same for every hotel: an h2 for the name, an h3 for the address, and a table full of room data.
But all that can be generated from the hotel information, rather than being limited by the static DOM.
To see what I mean, here’s a repl doing much what you’re looking for, from what I understand.