-3

How to add item from items list to inventory and print it?

var items = {
    knife: {
        name: "Knife"
    }
};

var inventory = {};

//document.write(inventory....);

Or am I not understanding something and making everything wrong? maybe objects is wrong choice?

I want output just to print item name like knife. But not from var items - Print it from inventory

Everything should work like picking up item from ground.

1 Answers1

1

You are probably using the wrong data structure for your inventory, unless you want to be able to pickup a single item per kind, you should be using an array.

var inventory = []; //empty inventory

inventory.push(items.knife); //pickup a knife
inventory.push(items.knife); //pickup another knife

Loop over the inventory and alert the item names:

for (var i = 0, len = inventory.length; i < len; i++) {
    alert(inventory[i].name);
}

Please note that the objects in the inventory are references to the items.knife object. If you want to clone those objects instead, have a look at What is the most efficient way to deep clone an object in JavaScript?.

Community
  • 1
  • 1
plalx
  • 42,889
  • 6
  • 74
  • 90