In the following example code, the function "getOriginalName" does not exist, but that is what I am looking for:
for(let variable of [var1, var2, var3]) {
console.log("Value: " + variable);
console.log("Name: " + getOriginalName(variable));
}
In my dreams, getOriginalName would return "var1", "var2" and "var3".
I know that you can access the name of variable "x" with:
varName = Object.keys({x})[0]
However, in my case this does not get me far, as the loop variable is called "variable" in each iteration.
So is there no way to iterate over a list of variables and still get the name of these variables?
2
Answers
Unfortunately, there is no built-in way to achieve this in JavaScript, as variable names are not accessible during runtime. However, you can work around this limitation by using an array of objects, where each object contains the variable name as a key and its value as the corresponding value. Here’s an example:
This code will produce the following output:
This workaround allows you to keep track of both the variable names and their values during iteration. Note that this approach requires you to manually create and maintain the
variables
array, which may not be ideal for all use cases.Based on your comment, you can use an object containing key value pairs: