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
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.