javascriptmongodbecmascript-6lexical-scopedynamic-scope

Dynamic scoping in Javascript similarly to Mongo


I have been trying to wrap my head around Dynamic Scoping, I love that with MongoDB you have the option to scope with strings, for example (this is pseudo and has not been tested)

const data = Schema.find({"scope.to.nested": "hello"})

console.log(data)
> [{scope: { to: {nested: "hello"}}}]

How would you accomplish the same thing in Javascript. Maybe something like

console.log(data["scope.to.nested"])
> "hello"

I have been trying to think of a way to ask this as clear as possible, so please ask for clarification if I am just pouring unfiltered thoughts onto the internet with no real coherent expectations 😂


Solution

  • You can achieve this with a JavaScript function:

    function getProperty(obj, path) {
        let currentObject = obj;
        let currentIndex = 0;
        
        while (true) {
            let dotIndex = path.indexOf('.', currentIndex);
            let propName = (dotIndex !== -1) ? path.substring(currentIndex, dotIndex) : path.substring(currentIndex);
            currentObject = currentObject[propName];
            
            if (dotIndex === -1)
                break;
            
            currentIndex = dotIndex + 1;
        }
        
        return currentObject;
    }
    

    You will need to use a function call to access the property, so for your example you will need to use getProperty(data, 'scope.to.nested'). If you want to do this with the JavaScript property access operator (data['scope.to.nested']), you can use proxies.

    Note that what you are asking for is different from dynamic scoping.