Clint Clint - 7 months ago 26
jQuery Question

Why does this code overwrite my object when i want it to add to the object

I have the following code. It all works exactly as i wish except for one thing. When a user enters another item_name (leaving room_name as is) it wipes the original item_name. What I require is for it to add another item into the object

<div class="container">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" name="room_name" id="room_name" class="form-control" placeholder="Room name">
<div class="form-group">
<input type="text" name="item_name" id="item_name" class="form-control" placeholder="Item name">
<div class="form-group">
<input type="text" name="item_description" id="item_description" class="form-control" placeholder="Item description">
<div class="form-group">
<input type="text" name="inventory" id="inventory" class="form-control" placeholder="DEBUG">
<div class="form-group">
<a id="submitinv" class="btn btn-success btn-block">Submit</a>
<table id="list" class="table table-striped">
<th>ROOM NAME</th>
<th>ITEM NAME</th>

roominventory = {};
obj = {};
room_name = $('#room_name').val();
item_name = $('#item_name').val();
item_description = $('#item_description').val();
obj[item_name] = item_description;
roominventory[room_name] = obj;
obj = {};
$('#list').append('<tr><td>' + room_name + '</td><td>' + item_name + '</td><td>' + item_description + '</td></tr>');



When we tell our worker:

roominventory[room_name] = obj

What we are saying is:

Find the key on the object roominventory that is equivalent to the
value room_name. I now want you to assign the value of obj to that key.

It sounds like that is not what you are wanting to tell your worker. What it sounds like you are wanting to tell your worker is:

Find the key on the object roominventory that is equivalent to the
value room_name. Now add the object to that value. 

There are a few ways to do this, the easiest being making each key in the roominventory object be an array doing something like this:

// First we check if we have messed with this key before
if(roominventory[room_name] !== undefined){
  // if we have, let's just push our new object onto the list
  // if we haven't, let's create a list of a single item to add to later
  roominventory[room_name] = [obj]