Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Path Resolver With JavaScript Proxies

| Comments

So today morning, when I was lurking on #javascript channel on freenode, there was this question:

merpnderp> If I have var foo = {x:{y:{z:bar}}}; And I have var keys = ['x','y','z']; How would I make something like foo[[keys.join('.')]] = 'baz'; work?

Me and @doodadjs were trying to solve this using [].reduce and then there was this silly thought of extending the same code to proxies

So, here is the code:

1
2
3
4
5
6
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 one could do something like:

1
obj['a'] = {b: {c : 1}}

and then obj['a.b.c'] would be equivalent to obj['a']['b']['c'] and not to worry non-existing keys would just return undefined as in

obj['a.x.c'] would return undefined.

P.S: Havn't checked the perfs yet, but this was just for the fun of it!

Comments