Parse dot notation to nested object

Takes an object with keys containing dot notation and parses them into objects.

by Brandon Shelley

JavaScript

(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"
}

$('body').append("<pre>" + JSON.stringify(Object.expand(obj), undefined, 4) + "</pre>");