javascript - 浅拷贝未在嵌套 JSON 对象 javascript 中更新

标签 javascript json angularjs

我有一个像这样的嵌套 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/

相关文章:

json - Oracle:以 JSON 格式返回行?

javascript - 从 Web 应用程序发布到数据库失败

php - 将 PHP 变量从 while 循环传递到 javascript 函数

javascript - 为什么 Axios get call 在基本设置下会返回 404 错误?

javascript - 我注意到我倾向于在 JavaScript/jQuery 中创建 DOM 对象并附加它们。这样可以吗还是我应该用 HTML 创建它们?

javascript - getUserMedia() 的解析约束无法正常工作 (WebRTC)

python - Python 中的 JSON 导航 (PowerBI API)

java - 通过使用超过 1 个深度级别的 map 从 csv 转换为 json

angularjs - SEO:Google 如何索引 Angular 应用程序 2016

javascript - iScroll5 和 Angularjs 1.2 不工作