JSFiddle - React, Tailwind, and code Playground
by MegaScience
JavaScript
const resolve = function (tree, base = self, sep = '.') {
if(!Array.isArray(tree)) {
if(typeof tree === 'string') tree = tree.replace(/\[['"]?(\w+)['"]?\]/g, '.$1').split(sep)
else throw 'Tree not array or string.'
}
console.log(tree, base.cat, window.cat)
return tree.reduce((prev, curr) => prev && prev[curr], base)
}
/*function r(path, obj=self, separator='.') {
var properties = Array.isArray(path) ? path : path.split(separator)
return properties.reduce((prev, curr) => prev && prev[curr], obj)
}*/
const cat = {
dog: {
mouse: 'potato'
}
}
console.log(resolve('cat.dog.mouse'), cat.dog.mouse, resolve('onload'), onload)