Creating a new array within an object and accessing its values


#1


I was reading a book about objects and arrays and about creating more complex data structures like arrays within objects. The example it gave was like this:

Hotel Room Charges
Room 1 = 5, 10, 10
Room 2 = 9, 75, 6
Room 3 = 19, 8, 1

And it said to create an object with property room1, room2, room3 and create an array called "item" for each property containing the numbers. It didn't show an example of how the object code looks like but it did say to access different charges of the rooms to use:


costs.room1.item[1];

From this i assumed the code would look something like this:

var costs = {
     room1: item[5, 10, 10]
};

but this didn't work and later realized I had to remove the "item" from the array. And the way to access the array properly would be as such:

var costs = {
     room1: [5, 10, 10]
};

costs.room1[1]    // 10

I know the book may not be perfect and have errors but is there an actual viable way to access arrays within an object by using the book's code answer

costs.room1.item[1];

and is there a way to create an array within an object with its own variable instead of a key?


#2

what you could do is nest a object inside a object, which means room can have multiply properties + values:

var costs = {
     room1: { 
         item: [5, 10, 10],
     },
     room2: {
         item: [9, 75, 6]
     }
};
console.log(costs.room1.item)

#3

this way, room1 is a object, which allows you to item as a variable for the array, but technically item would now be considered a key as well.


#4

I guess this is a roundabout way of getting the book's answer to work

costs.room1.item[1] //10

to access the array's 2nd index value and get 10. But then wouldn't this be considered an "array within an object within an object"? The book only said "an array within an object" so that was what had me confused.


#5

yes, it would. i wouldn't know a better way to satisfy that book of yours.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.