'How to convert object notation to a string

Let's say we have an object

export const hello = {
 a: 1,
 b: 2
}

and we import it and have a function

import { hello } from ...

function printVarName(x) {
 ...
}

printVarName(hello.b)

How can we convert hello.b to a string 'hello.b'?

The goal to be able to create the string 'hello.b' from the variable x inside of printVarName in this example.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abir Taheer