Convert javascript dot notation object to nested object

后端 未结 7 1283
我在风中等你
我在风中等你 2020-11-28 09:54

I\'m trying to build a function that would expand an object like :

{
    \'ab.cd.e\' : \'foo\',
    \'ab.cd.f\' : \'bar\',
    \'ab.g\' : \'foo2\'
}
<         


        
7条回答
  •  生来不讨喜
    2020-11-28 10:40

    Derived from Esailija's answer, with fixes to support multiple top-level keys.

    (function () {
        function parseDotNotation(str, val, obj) {
            var currentObj = obj,
                keys = str.split("."),
                i, l = Math.max(1, keys.length - 1),
                key;
    
            for (i = 0; i < l; ++i) {
                key = keys[i];
                currentObj[key] = currentObj[key] || {};
                currentObj = currentObj[key];
            }
    
            currentObj[keys[i]] = val;
            delete obj[str];
        }
    
        Object.expand = function (obj) {
            for (var key in obj) {
                if (key.indexOf(".") !== -1)
                {
                    parseDotNotation(key, obj[key], obj);
                }            
            }
            return obj;
        };
    
    })();
    
    var obj = {
        "pizza": "that",
        "this.other": "that",
        "alphabets": [1, 2, 3, 4],
        "this.thing.that": "this"
    }
    

    Outputs:

    {
        "pizza": "that",
        "alphabets": [
            1,
            2,
            3,
            4
        ],
        "this": {
            "other": "that",
            "thing": {
                "that": "this"
            }
        }
    }
    

    Fiddle

提交回复
热议问题