Clint Clint - 1 month ago 14
jQuery Question

Key name in associative array

I'm trying to add items to an associative array but my key name is not being generated properly. My code is as follows:

var room_name = $('#room_name').val();
var item_name = $('#item_name').val();
var item_description = $('#item_description').val();
roominventory[room_name] = { item_name : item_description };


What is happening is I am getting

{
"Correct room name": {
"item_name": "correct item description"
}
}


Everything works except the
item_name
. I would like the key name to be the value of
item_name
but instead I'm just getting the text
item_name
.

Any ideas what I'm doing wrong?

Answer

As Rory pointed out, you can't use variables in key. you have to use an object which holds the key and value:

//wrong one
var roominventory = {};
var room_name = "something";
var item_name = "something item";
var item_description = "something description";
roominventory[room_name] = {item_name : item_description};
console.log(roominventory);

//correct way
var roominventory1 = {};
var room_name = "something";
var item_name = "something item";
var item_description = "something description";
var obj = {};
obj[item_name] = item_description;
roominventory1[room_name] = obj;
console.log(roominventory1);

https://jsfiddle.net/u2j42wsv/

Comments