JSFiddle - React, Tailwind, and code Playground

by Derek Leung

HTML

<pre></pre>

JavaScript

myObject = {
    a:{
        value: "a will be extended",
        b: "This will be written over"
    }
};

Object.prototype.extendWithPath = function(path, value) {
    var obj = this,
        levels = path.split("."),
        i = 0;

    function createLevel(child) {
        var name = levels[i++];
        if(typeof child[name] !== "undefined" && child[name] !== null) {
            if(typeof child[name] !== "object" && typeof child[name] !== "function") {
                console.warn("Rewriting " + name);
                child[name] = {};
            }
        } else {
            child[name] = {};
        }
        if(i == levels.length) {
            child[name] = value;
        } else {
            createLevel(child[name]);
        }
    }
    createLevel(obj);
    return obj;
}

var path = "a.b.c",
    value = "ciao";

myObject.extendWithPath(path, value);


console.log(myObject.a.b.c) //will print "ciao"
document.querySelector("pre").innerHTML = JSON.stringify(myObject, " ", 4);