Bryan
Bryan

Reputation: 17581

Object Not Maintaining Assigned Values

I am looping through an array to create another array of objects in a modified format.

for (i = 1; i <= 37; i++) { // create 37 boxes for days of the month and nearby dates
  room_reservations[i] = {};
  var this_date = getDate();
  var res_count = 0;
  for (var res_index = 0; res_index < reservations.length; res_index++) {
    var this_res = reservations[res_index];
    // bad assignment location
    // res_room = JSON.parse(JSON.stringify(this_res));
    if (this_res.checkin <= this_date && this_res.checkout > this_date) {
      for (var k = 0; k < this_res.rooms.length; k++) {
        var res_room = {};
        res_room = JSON.parse(JSON.stringify(this_res));
        var this_room = res_room.rooms[k];
        res_room.room_index = k;
        var traveler_count = this_room.travelers.length;
        console.log('traveler_count: ', traveler_count);
        res_room.traveler_count = traveler_count;
        //traveler_counts[i][res_room.room_name] = traveler_count;
        console.log('res_room.traveler_count: ', res_room.traveler_count);
        var room_name = this_room.room_name;
        console.log('room_name: ', room_name);
        res_room.room_name = room_name;
        console.log('res_room: ', res_room);
        room_reservations[i][res_room.room_name] = res_room;
      }
    }
  }
}

Essentially, I console log the object property traveler_count and get the correct value. But when logging the entire object, the property value is incorrect. It's like it grabs the value from the next loop.

enter image description here

How do I fix this? It is not just the logging. The values being set are wrong in the room_reservations array. For example, I set the attribute name to res_room.room_name and the value to res_room. But the attribute name does not match the value in the object.

enter image description here

Please help. Thx

Upvotes: 1

Views: 60

Answers (1)

Barmar
Barmar

Reputation: 780974

The problem is that you're using the same res_room object every time through the for (var k) loop. So all the properties in res_room[i] are referring to the same object, which you modify in place. You need to make a copy of the object when you assign it.

room_reservations[i][res_room.room_name] = JSON.parse(JSON.stringify(res_room));

Upvotes: 1

Related Questions