在javascript中动态更新嵌套对象[重复]

2024-03-01

我有一个从 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

or

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

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


您应该能够使用括号符号沿着您的对象走下去[]依次访问每个属性:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在javascript中动态更新嵌套对象[重复] 的相关文章