简体   繁体   中英

not able to dynamically access an object property using a variable

I am trying to add find a property of an object using a variable but it is not working. When I write the object name iso of the variable, it is working, although the variable and the object name are exactly the same..

function calCulate(nrs){
const product = {DE2599:{name:"tet", bar:2.5, price: 3.5}};
var nr = document.getElementById(nrs).value;
var sku = ("prod" + nr);
var qty = ("qty" + nr);
var pric = ("price"+nr);
var pal = ("pallet"+nr);
var ctry = document.getElementById('country').value;
var x = document.getElementById(qty).value;
var test = document.getElementById(prod).value;
var tests = test.toString(); // way of getting the result
var testr = tests.indexOf(" "); // way of getting the result
var testt = tests.slice(0,testr); // way of getting the result
var uniqueID = ctry+testt; // this value returns DE2599
var mywindow = window.open('','PRINT','height=800,width=800');
var ter = product.uniqueID; // I use uniqueID because it can vary 
var tar = ter.price;
mywindow.document.write(tar); // this is not showing any result; but if I change the uniqueID with the actualy key, ie DE2599, it is working correctly

uniqueId is not a property of product so your ter will be storing undefined (and you should be getting an error for tar ).

When you need to use the value of a variable to access the property of an object, you need to use bracket notation.

 const product = {DE2599:{name:"tet", bar:2.5, price: 3.5}}; let uniqueId = 'DE2599'; console.log('with dot notation'); console.log(product.uniqueId); console.log('with bracket notation'); console.log(product[uniqueId]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM