This is impossible. See the answer to: Determine original name of variable after its passed to a function
There's no way to know what the original name of a variable is after its value has been passed to a function.
The closest thing that I can come up with is the following:
The solution involves installing the dot-prop
package that's built to parse strings and find the associated property in an object. https://www.npmjs.com/package/dot-prop
Disclaimer: I have no association to the package itself
It does also involve changing up your implementation since you also now need to pass the object that you're referencing itself.
import { getProperty } from 'dot-prop';
import { hello } from ...
function printVarName(obj, path) {
const value = getProperty(obj, path);
console.log(path, value);
}
printVarName({hello}, 'hello.b')
We're doing a destructuring assignment in the object provided as the first parameter.
Passing { hello }
will pass an object that's the same as { hello: hello }
and so when you use the getProperty
method it can then find the hello variable and its nested values.
The first parameter is necessary if you're going to be passing variables from outside the scope of the function definition. Otherwise you can create a constant object with all of the variable values and that would let you remove the need for the first parameter where you provide the object.