Search code examples
javascriptjqueryextend

Extend a JavaScript object by passing a string with the path and a value


Is there an easy way to extend a JavaScript object by passing a string and a value?

Basically I need something like this:

myObject = {}

var extendObj = function(obj, path, value){
}

var path = "a.b.c", value = "ciao";
extendObj(myObject, path, value);


console.log(myObject.a.b.c) //will print "ciao"

Solution

  • myObject = {};
    
    var extendObj = function (obj, path, value) {
        var 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";
    extendObj(myObject, path, value);
    
    
    console.log(myObject.a.b.c) //will print "ciao"
    

    http://jsfiddle.net/DerekL/AKB4Q/

    enter image description here

    You can see in the console that it creates the path according to path you entered.