To simplify the process, using a basic array of strings can be effective. Here's a concise code snippet for achieving this task (originally shared by me in another
answer):
function get(obj, property) {
var current = obj;
for (var i = 0, l = property.length; i < l; ++i) {
if (Object(current) === current) current = current[property[i]];
else {
current = undefined;
break;
}
}
return current;
}
For example:
get(obj, ['nestedObj', 'My key has spaces']); // "You want my value"
If the property is not found, the function will simply return undefined
. However, it's easy to modify the code to throw an error according to typical JavaScript behavior when accessing a property on undefined or null.
In case you prefer using the exact property string syntax, a parser I developed previously may come in handy, although it's quite basic. This parser employs regular expressions to extract segments from the string and assemble them into an array. It then traverses the array to locate nested values within an object passed as input.
The parsing algorithm accommodates escape sequences, strings, plain numbers, and dot property access. The only limitation lies in referencing actual variables and utilizing invalid identifiers at the beginning, which I am currently working on resolving.
Here's an illustration:
evaluateProperty({ test: { 'space space': 1 } }, 'test["space space"]'); // 1
The script used for parsing:
function parsePropertyString(str) {
// Code for parsing goes here...
}
function evaluateProperty(obj, str) {
var propertyChain = parsePropertyString(str);
for (var i = 0; i < propertyChain.length; ++i) obj = obj[propertyChain[i]];
return obj;
}
// Additional regex creation to optimize performance
function createStrRegex(type) {
return new RegExp(
'^' + type + '(?:[^' + type +
'\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[^xu\\d\\r\\n\\u2028\\u2029]|0(?!\\d)|x[\\da-fA-F]{2}|u[\\da-fA-F]{4})|(?:\\r\\n|[\\r\\n\\u2028\\u2029]))*?' +
type + '$'
);
}
var singleQuoteStr = createStrRegex("'");
var doubleQuoteStr = createStrRegex('"');