我有一个像这样的嵌套 JSON 对象:
var jsonObj =
{ "level1" :
{ "status" : true,
"level2" : {} // and it has the same format and can go to level3, 4, etc
}
}
我想要做的很简单,我想要到达 Level2,并向其添加一个新的 Level3 对象。 基本上我想在下面执行以下代码,但由于级别是动态的,我需要一个遍历我的对象的函数。
obj.Level1.Level2.Level3 = { 'status' : true}
这是我的代码片段:
function updateStatusForLevel(nestedObj, categoryHierarchy){
// categoryHierarchy that is passed = ['Level1', 'Level2', 'Level3'];
var obj = nestedObj;
angular.forEach(categoryHierarchy, function(value, key){
obj = obj[value];
if (key === categoryHierarchy.length - 1 && angular.isUndefined(obj)){
obj[value] = {}; // I want to add 'Level3' = {}
}
});
obj.status = 'true'; // and finally, update the status
console.info("my original obj is " + JSON.stringify(nestedObj));
}
但是我似乎错过了一些东西。如果我这样做,我原来的nestedObj仍然与我传入的相同(它没有更新,只有obj
对象被更新。我相信这应该是一个非常简单的代码,遍历嵌套的JSON对象。为什么浅拷贝没有更新原始对象?
最佳答案
也许是这样的
function updateStatusForLevel(nestedObj, categoryHierarchy){
// categoryHierarchy that is passed = ['Level1', 'Level2', 'Level3'];
if(categoryHierarchy.length) {
var shifted = categoryHierarchy.shift();
nestedObj[shifted] = {status: true};
return updateStatusForLevel(starter[shifted], categoryHierarchy);
} else {
return nestedObj;
}
}
然后调用 updateStatusForLevel(nestedObj, ['level1', 'level2', 'level3'])
会将 nestedObj
修改为
level1: Object
level2: Object
level3: Object
status: true
status: true
status: true
注意,这个答案并不聪明,所以最好有 plnkr 或其他更好的 asnwer,但现在,在浏览器开发控制台中尝试这个
关于javascript - 浅拷贝未在嵌套 JSON 对象 javascript 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645345/