Convert string with dot notation to JSON

前端 未结 3 1755
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 23:03

Given a string as dot notation, how would I create an object from that string (checking for already existing properties): eg

var obj = {};
stringToObj(\'a.b\         


        
3条回答
  •  無奈伤痛
    2020-12-04 23:37

    You can take advantage of references:

    function stringToObj(path,value,obj) {
        var parts = path.split("."), part;
        while(part = parts.shift()) {
            if( typeof obj[part] != "object") obj[part] = {};
            obj = obj[part]; // update "pointer"
        }
        obj["_x"] = value;
    }
    

提交回复
热议问题