javascript对象 - 使用递归函数

时间:2015-05-19 06:29:11

标签: javascript javascript-objects

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

如何动态设置嵌套属性?

它只能使用一个级别属性,我无法设置下一个内部级别....

我的代码:

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

1 个答案:

答案 0 :(得分:1)

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

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