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

后端 未结 4 1278
滥情空心
滥情空心 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:04

    My version:

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

    Working demo: http://jsfiddle.net/jfriend00/Sxz2z/

提交回复
热议问题