Generally the errors you receive in the console do not lie. So let's break your object down, and see what could possibly cause the error.
var roomName = 'room_' + $(this).data('room-id');
beds_required_obj.roomName.single_beds_required = ...
Now the code above firstly assumes that beds_required_obj
is an object that exists. We can see by the comments that this is indeed true, as you used:
var beds_required_obj = {};
Now because this object exists, you can call beds_required_obj.anything_here
, and it will be valid code. However, the child you attempt to access may not exist.
Next you have written beds_required_obj.roomName
. Now this is attempting to access a child object named 'roomName', not 'room_id'. In order to access the dynamic name that you have stored in the roomName
variable, you need to use square brackets. So:
beds_required_obj[roomName]
This will return the child object of the dynamically created room name.
Now depending on what roomName
actually is (it might be 'room_123' for example), this child object also might not exist. If it does not exist, then any attempt to access a child of this object will return your error. For example, look at the code below:
var beds_required_obj = []; // create an empty object
var roomName = 'room_1234'; // the name of our room
// this line below will throw an error because the room_1234 child object does not exist
beds_required_obj[roomName].single_beds_required = 2;
What is happening is that you are trying to access single_beds_required
as a child of an undefined object. To make this work, you would need to change the code above to include an extra line:
var beds_required_obj = []; // create an empty object
var roomName = 'room_1234'; // the name of our room
// now create the room child object
beds_required_obj[roomName] = {};
// now this line will work, as the room is a valid object that can have children assigned to it.
beds_required_obj[roomName].single_beds_required = 2;
Note: If you want to do something like this with more readable code (imo), then I would use:
breds_required_obj[roomName] = {
single_beds_required: 2
};