Hemanth's Scribes

javascript

Path Resolver with JavaScript Proxies

Author Photo

Hemanth HM

A question from #javascript on freenode: How to access foo['x']['y']['z'] using foo['x.y.z']?

Solution with Proxies

var handler = {
  get: function(target, path) {
    return path.split(".").reduce(
      (o, k) => o && (k in o) ? o[k] : undefined,
      target
    );
  }
};

var obj = new Proxy({}, handler);

Now you can do:
javascript
obj['a'] = { b: { c: 1 } };
obj['a.b.c']; // 1
obj['a.x.c']; // undefined (safe!)

Just for the fun of it! 🎉

#javascript#es6#proxy