在javascript中动态更新嵌套对象

时间:2015-02-26 18:23:40

标签: javascript jquery arrays json object

我有一个从json解码的对象:

var data = [{
    "parentSeries":1,
    "children":[{
        "BusinessRule":"ChrisTest2",
        "ID":"ChrisTest2||3",
        "childsub":3,
        "jsonCondition":{
            "parentSeries":1,
             "children":[{
                 "RuleDefinition":"ChrisTest2||3",
                 "ID":"ChrisTest2||3||CondField1",
                 "Field":"CondField1",
                 "Test":"=1"
             },{
                 "RuleDefinition":"ChrisTest2||3",
                "ID":"ChrisTest2||3||CondField2",
                "Field":"CondField2",
                "Test":"=2"
             }]
        }
    }]
}]

我想动态更新此对象的任何元素。我有一个数组,告诉我我想要更新的属性是什么。例如:

var splitMap = ["jsonCondition", "children", "0", "Test"]

我有一个值,我希望更新此数组中的最后一个条目(newValue),并且我有一些代码来更新特定的嵌套项以包含这个新值:

if (splitMap.length > 0) {
    var newdata = data;
    for (var p = 0; p < splitMap.length-1; p++) {
        newdata = newdata[splitMap[p]];
    }
    newdata[splitMap[splitMap.length - 1]] = newValue;
}

但我无法找到一种方法来更新原始数据!我基本上想做

oldobject['jsonCondition']['children'][0] = newdata

oldobject['jsonCondition']['children'][0]['Test'] = newValue

...但我想根据地图数组的内容和长度计算出这条路径的键和深度。如果有帮助的话,我在我们的平台上有jquery($ .each?)!有任何想法吗?谢谢:))

1 个答案:

答案 0 :(得分:1)

您应该能够使用括号表示[]依次访问每个属性,从而沿着对象走下去:

var curr = oldobject;   // this keeps track of our current position
for (var i=0; i < splitMap.length-1; i++) {
    if (curr.hasOwnProperty(splitMap[i]) {
        curr = curr[splitMap[i]];
    }
    else {
       // your map is wrong! Up to you how to handle this error
    }
}
curr[splitMap[i]] = newValue;    // for the last property, we set the value