javascript object - 使用递归函数动态设置嵌套值

javascript object - Dynamically setting a nested value using recursive function

我正在尝试设置嵌套子对象属性之一,但嵌套级别是动态的。

如何动态设置嵌套属性?

它只对一个级别的属性起作用,我无法设置下一个内部级别....

我的代码:

function deSerialize(qualifiedNameArray, currentIndex, resultJSON, valueToBeInitializedForFinalNode)
{
    if (currentIndex  == (qualifiedNameArray.length - 1)){
        resultJSON [qualifiedNameArray[currentIndex++]] = valueToBeInitializedForFinalNode;
    }
    else
    {
        resultJSON [qualifiedNameArray[currentIndex++]] = {};
    }

    if (currentIndex < qualifiedNameArray.length)
        deSerialize( qualifiedNameArray, currentIndex, resultJSON, valueToBeInitializedForFinalNode);

    return resultJSON;
}


  var results = {"columnname":"person.name.first", "varcharvalue":"david", "objecttype" : "user"};
    var valueToBeInitializedForFinalNode = results["varcharvalue"];
    var qualifiedNameArray = results["columnname"].split('.');
    var resultJSON = {};
    deSerialize(qualifiedNameArray, 0, resultJSON, valueToBeInitializedForFinalNode);

一个简单的解决方案可能是,不确定这是否是您要找的:

function makeObj(arry, initValue){
    var obj = {}, objRef  = obj, idx = 0;    
    while(idx < arry.length -1){
        obj[arry[idx]] = {};
        obj = obj[arry[idx]];
        idx++;
    }
    obj[arry[idx]] = initValue;
    return objRef;
}

用法:

resultJSON = makeObj( qualifiedNameArray, valueToBeInitializedForFinalNode);

另一种方式是:

function makeObj(objRef, arry, initValue){
    var obj = objRef, idx = 0;    
    while(idx < arry.length -1){
        if(!obj[arry[idx]]) obj[arry[idx]] = {};
        obj = obj[arry[idx]];
        idx++;
    }
    if(!obj[arry[idx]]) obj[arry[idx]] = initValue;
}

这样,您不会更改任何可能已经存在的值,用法:

makeObj( resultJSON, qualifiedNameArray, valueToBeInitializedForFinalNode);