如何使用分隔字符串来定位和修改任意深度的对象键?

时间:2014-05-14 21:29:14

标签: javascript multidimensional-array

这是解决问题的问题;没有什么是错的,我只是对如何前进感到难过。基本上我希望我的用户能够

  1. 通过"路径"的字符串表示,指向具有任意深度的对象的任意键。
  2. 确认"路径"的每一步。存在;和
  3. 实施类似CRUD的功能
  4. 我可以验证每个密钥是否有效,但我只是在没有最终使用eval()语句的情况下如何利用所述路径而烦恼,但当然我不需要解释为什么我和#39;我不打算让eval()的电话接近任意用户输入。就我而言:

    const SEP = "/" //in reality this is set by the server,
    MyObjInterface = function() {
        this.params = {};
        this.response = {};
    
        // suppose some initialization business, then on to the question... ( >.>)
    
        this.updateOb= function(path, value ) {
            path = path.replace('\\' + DS,"$DIRECTORY_SEPARATOR").split(DS);
    
            for (var i = 0; i < path.length; i++) {
                path[i].replace("$DIRECTORY_SEPARATOR",DS);
            }
    
            if (typeof(path) != "object" || path.length < 3) { // 3 = minimum depth to reach a valid field in any rset scheme
                throw "Could not create rset representation: path either incorrectly formatted or incomplete."
            }
    
            var invalidPath = false;
            var searchContext = path[0] === "params" ? this.params : this.response;
            for (var i = 1; i < path.length - 1; i++) {
                if (invalidPath) { throw "No key found in rset at provided path: [" + path[i] + "]."; }
    
                if (i === path.length - 1) {
                    searchContext[path[1]] = value;
                    return true;
                }
                if (path[i] in searchContext) {
                    searchContext = searchContext[path[i]];
                } else {
                    invalidPath = true;
                }
    
            }
        }
    };
    

1 个答案:

答案 0 :(得分:1)

您将路径分解为组件,然后递归遍历树。

我的JS很弱,所以我会伪代码。

path = "go.down.three";
listOfElements = breakUpPath(path); // Now listOfElement = ["go", "down", "three"];
myObj = setObjectValue(myObj, listOfElement, "I'm a value");

function setObjectValue(obj, listOfElements, value) {
    var firstPart = pop(listOfElements); // get and remove top of listOfElements stack
    if (length(listOfElements) == 0) { // last element of the path, set the value
        obj[firstPart] = value;
        return obj;
    } else {
        // check if a property exists at all
        var firstValue = obj[firstPart];
        if (firstValue == null) {
            firstValue = new Object();
            obj[firstPart] = firstValue;
        }
        obj[firstPart] = setObjectValue(firstValue, listOfElement, value);
    }
}

所以,正如我所说,我的JS很弱(非常弱,我甚至不能拼写JavaScript)。不用说,这是未经测试的。

但类似的东西是你正在寻找的东西。沿着路径的元素向前走。