Home > Software design >  Unable to use a variable key index in an object call
Unable to use a variable key index in an object call

Time:10-06

I have a line in JavaScript, which is working fine:

var fetchedValue = getMyData(available_values.data[0].actualKey);

But if I replace the static portion actualKey with the dynamic variable var1 and use it, it gives error that "TypeError: Cannot read properties of undefined (reading 'length')"

var var1 = "actualKey";
var fetchedValue = getMyData(available_values.data[0].eval(var1));

I tried writing multiple occurrences, such as below, but everything is giving the same error:

var fetchedValue = getMyData(available_values.data[0].eval({var1}));

and

var fetchedValue = getMyData(available_values.data[0].eval(${var1}));

CodePudding user response:

Use bracket notation. See property accessors.

available_values.data[0][var1]

CodePudding user response:

Try this:

const myPropName = "actualKey";
var fetchedValue = getMyData(available_values.data[0][myPropName]);
  • Related