Josh Feinsilber
Josh Feinsilber

Reputation: 33

How to convert dot notation to string?

I was looking for a way to convert something in dot notation into a string using Javascript. Basically here's what I am looking for:

function dotToString(dotNotation){
  return something;
}


dotToString(this.is.just.a.test);
// Would return "this.is.just.a.test"

Upvotes: 0

Views: 376

Answers (2)

user663031
user663031

Reputation:

Yes, you can do this with proxies.

function makeDotProxy(name) {
  return new Proxy({}, {
    get(target, prop) {
      if (prop === 'valueOf' || prop === 'toString') return () => name;
      if (typeof prop === 'symbol') return Reflect.get(target, prop);
      return makeDotProxy(name + '.' + prop);
    }
  });
}

const This = makeDotProxy('this');
console.log(This.is.a.just.a.test.toString());

But then, why would you want to?

Upvotes: 1

Blue
Blue

Reputation: 22911

Short answer: No

Long answer: When javascript passes an argument to a function, it passes in the value from the variable you are attempting to pass in. At no point does the dotToString function see this.is.just.a.test (It would see "blah", if this.is.just.a.test = "blah"). This is not possible.

Upvotes: 3

Related Questions