Setting a depth in an object literal by a string of dot notation?

后端 未结 4 1274
滥情空心
滥情空心 2020-12-10 09:37

There are plenty of solutions out there to check/access an object literal giving a string of dot notation, but what I need to do is SET an object literal based on a string o

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 10:05

    This is one way of doing it:

    function setDepth(obj, path, value) {
        var levels = path.split(".");
        var curLevel = obj;
        var i = 0;
        while (i < levels.length-1) {
            curLevel = curLevel[levels[i]];
            i++;
        }
        curLevel[levels[levels.length-1]] = value;
    }
    

    Working demo.

提交回复
热议问题