JSFiddle - React, Tailwind, and code Playground
JavaScript
function getProperty(obj, prop) {
var parts = prop.match(/[^.\[\]'"]+/g),
i = 0,
current = parts[0];
var currentValue = obj;
while (currentValue[current]) {
currentValue = currentValue[current];
current = parts[++i];
}
if(i < parts.length) {
return undefined;
}
return currentValue;
}
var someObject = {
"foo": {
"bar": {
"baz": [{
"foo bar": "baz",
"baz foo": "bar",
"bazfoo": "bar"
}]
}
}
};
var test1 = "foo.bar.baz[0]['bazfoo']";
var test2 = "foo.bar.baz[0]['foo bar']";
//My required result from test1 is 'bar'
alert(test1 + ' is ' + getProperty(someObject, test1));
//My required result from test2 is 'baz'
alert(test2 + ' is ' + getProperty(someObject, test2));