Create an object out of dot notation

前端 未结 7 1216
小鲜肉
小鲜肉 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 02:05

    Off the top of my head I guess you can do something like this:

    function addValueToObj(obj, newProp) {
        newProp = newProp.split("=");       // separate the "path" from the "value"
    
        var path = newProp[0].split("."),     // separate each step in the "path"
            val = newProp.slice(1).join("="); // allow for "=" in "value"
    
        for (var i = 0, tmp = obj; i < path.length - 1; i++) {
           tmp = tmp[path[i]] = {};     // loop through each part of the path adding to obj
        }
        tmp[path[i]] = val;             // at the end of the chain add the value in
    }
    
    var x = {a:1, b:2};
    addValueToObj(x, "c.d=3");
    // x is now {"a":1,"b":2,"c":{"d":"3"}}
    addValueToObj(x, "e.f.g.h=9=9");
    // x is now {"a":1,"b":2,"c":{"d":"3"},"e":{"f":{"g":{"h":"9=9"}}}}
    

    Demo: http://jsfiddle.net/E8dMF/1/

提交回复
热议问题