Convert string with dot notation to JSON

前端 未结 3 1749
隐瞒了意图╮
隐瞒了意图╮ 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:18

    To expand on both @ilikeopensource and @Niet the Dark Absol answers, I needed to add the support for arrays (multiple instances of the same path) with the possibility for nested objects. My case was more of a hybrid of dot notation and json strings.

    function stringToObj(path, value, obj) {
        var objValue = value;
        try {
            objValue = JSON.parse(value);
        } catch (e) { } //eat the error, must not be json so carry on... Hack to do a valid JSON check
    
        var parts = path.split("."), part;
        var last = parts.pop();
        while (part = parts.shift()) {
            if (typeof obj[part] != "object")
                obj[part] = {};
            obj = obj[part];
        }
        if (obj.hasOwnProperty(last) && obj[last] && obj[last].constructor === Array) {
            obj[last].push(objValue);
        }
        else if (obj.hasOwnProperty(last) && obj[last]) {
            var objArray = [];
            objArray.push(obj[last])
            objArray.push(objValue);
            obj[last] = objArray;
        }
        else {
            obj[last] = objValue;
        }
    }
    

    Thanks guys for the help!

    0 讨论(0)
  • 2020-12-04 23:30

    For those of you who are looking for solution without the _x in the object try this code. A slight modification of the above code (which is brilliant)

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

    As bonus the above code will work if you want to update parts of an existing object :)

     var obj = {a:{b:3}};
     stringToObj("a.b",10,obj);
     console.log(obj); //result : {a:{b:10}}
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题