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

依然范特西╮ 提交于 2020-01-04 14:22:33

问题


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"

回答1:


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/

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



来源:https://stackoverflow.com/questions/16182141/extend-a-javascript-object-by-passing-a-string-with-the-path-and-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!