I have a 2d JavaScript array like this:
JavaScript
x
2
1
inventory[1].products
2
where products is an object with elements
{"itemid":"na", "books":10, "dvds":15, "cds":4}
I need to be able to set the itemid with something like
JavaScript
1
3
1
inventory[1].itemid = "books";
2
indirectaddress = inventory[1].itemid;
3
and then be able to read the value of the books element with something like:
JavaScript
1
2
1
numberofbooks = inventory[1].indirectaddress;
2
Is this possible with JS arrays? I done some searching and can’t find anything, unless I am not using the correct nomenclature.
Advertisement
Answer
You can remember the property name in your indirectaddress variable, and use bracket notation to access “books” property via indirectaddress.
JavaScript
1
3
1
indirectaddress = "books";
2
numberofbooks = inventory[1][indirectaddress];
3