It appears that you are looking to access a complex data structure programmatically, where the path is determined through parsing a specific syntax in a text query - using .
as the delimiter. Implementing a recursive function to navigate through the data structure based on the provided path may not be too challenging. However, a key issue highlighted in your query is when the initial item in the path refers to a variable, which poses difficulties as variables cannot be directly searched within the current context; only object keys can be searched for. For instance, if the variable settings
is a property of the global window
object, the search should commence from the window
object.
To address this, you aim to develop a method that accepts the root object (e.g., window
as mentioned earlier), checks the first element of the path against properties in that object, and recursively calls itself with the resulting object along with the remaining path components.
An elementary implementation could resemble the following:
function explorePath(obj, path) {
let [first, remaining] = path.split(".", 2);
if (obj[first] !== undefined) {
if (remaining.length > 0)
return explorePath(obj[first], remaining);
return obj[first];
}
return undefined;
}