Javascript 中的动态范围类似于 Mongo

问题描述

我一直在尝试围绕动态范围进行思考,我喜欢使用 MongoDB 您可以选择使用字符串进行范围,例如(这是伪的,尚未经过测试)

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

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

你会如何在 Javascript 中完成同样的事情。也许像

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

我一直在想办法尽可能清楚地提出这个问题,所以如果我只是在没有真正一致的期望的情况下将未经过滤的想法倾泻到互联网上,请要求澄清?

解决方法

您可以使用 JavaScript 函数实现此目的:

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;
}

您将需要使用函数调用来访问该属性,因此对于您的示例,您将需要使用 getProperty(data,'scope.to.nested')。如果要使用 JavaScript 属性访问运算符 (data['scope.to.nested']) 执行此操作,可以使用 proxies

请注意,您所要求的与 dynamic scoping 不同。