0

I'm using Ajax in order to get a list of items of an inventory, I would like to have an object named inventory and then create attributes named as the items of the response, so that means if I insert more items in my database I wouldn't need to hard code the elements of the object in my javascript file. Right now I'm able to create the object, but I can't access de dynamically created attributes and their values. I would like to alter the values with some user Input like pressing a button.

I've tried to use a Dictionary and searched but that didn't seem to work

var inventory = {};
  $.ajax({
url:"phpf/getItems.php",
type:"POST",
data:{},
success: function (data) {
  var result = JSON.parse(data);
  for (var index = 0; index < result.length; index++) {
    var str = String(result[index][0]);
    inventory[str] = 5;
  }
}
});
console.log(inventory["Cookies"]);
console.log(inventory[0]);

I would like to access the information of the object like inventory["something"] but console says it's undefined, and when I try to add the value to another number it says NAN as result

2 Answers 2

1

You can already access your data parsed from your JSON.parse, it returns an object so it can be called using the ['key'] accessor :

let json = '{"key1": 2, "key2": "test"}';
let values = JSON.parse(json);
console.log(values.key1);
console.log(values['key2']);

Sign up to request clarification or add additional context in comments.

Comments

0

Inventory is an object, so you want to access keys and values in your object using dot notation.

let inventory = 
{
   item1: "Cookie",
   item2: "Cake"
}
inventory.item3 = "Brownies";

console.log(inventory.item1);
console.log(inventory.item2);
console.log(inventory.item3);

Also to loop through an object you want to go like so:

for (var key in object) {
    //your code here
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.