Javascript: Convert String To Object Value Without `eval`

Allen Kim
1 min readMay 30, 2018

This is how to convert "foo.bar.fuz.baz" to the actual value of foo.bar.fuz.baz . If the value is not available, it returns undefined

function str2Val(str, scope=window) {
const keys = str.split(/[\.\[\]'"]/).filter(e => e);
let ret = scope;

try {
keys.forEach(key => {
ret = ret[key];
});
return ret;
} catch(e) {
return undefined;
}
}
// The following is for test
window.foo = {
bar: {
a: {
b: {
'c-end': 'hello'
}
}
}
}

--

--