Create an object out of dot notation

前端 未结 7 1167
小鲜肉
小鲜肉 2021-01-06 01:30

This is a reverse question to this question.

Given an object x={a:1,b:2} and a string c.d=3, modify object x to the following:



        
7条回答
  •  一整个雨季
    2021-01-06 01:59

    I believe dojo's setObject does what you want. If you (understandably) don't want to pull in all of dojo then I would recommend examining their (freely available) source or loading just base (only 4k) via AMD. It looks something like this :

    function setObject(name, value, context) {
        var parts=name.split("."), 
        p=parts.pop();
        for(var i=0, j; context && (j=parts[i]); i++){
            context = (j in context ? context[j] : context[j]={});
        }
        return context && p ? (context[p]=value) : undefined; // Object
    }
    

    So in your case you would do :

    x={a:1,b:2};
    setObject("c.d", 3, x);
    

    Warning : unless you only ever deal with trivial cases, I would urge you to still go check out the full dojo implementation, which deals with cases where no context is provided etc.

提交回复
热议问题