Convert javascript dot notation object to nested object

后端 未结 7 1196
我在风中等你
我在风中等你 2020-11-28 09:54

I\'m trying to build a function that would expand an object like :

{
    \'ab.cd.e\' : \'foo\',
    \'ab.cd.f\' : \'bar\',
    \'ab.g\' : \'foo2\'
}
<         


        
7条回答
  •  有刺的猬
    2020-11-28 10:27

    You need to convert each string key into object. Using following function you can get desire result.

     function convertIntoJSON(obj) {
    
                    var o = {}, j, d;
                    for (var m in obj) {
                        d = m.split(".");
                    var startOfObj = o;
                    for (j = 0; j < d.length  ; j += 1) {
    
                        if (j == d.length - 1) {
                            startOfObj[d[j]] = obj[m];
                        }
                        else {
                            startOfObj[d[j]] = startOfObj[d[j]] || {};
                            startOfObj = startOfObj[d[j]];
                        }
                    }
                }
                return o;
            }
    

    Now call this function

     var aa = {
                    'ab.cd.e': 'foo',
                    'ab.cd.f': 'bar',
                        'ab.g': 'foo2'
                    };
       var desiredObj =  convertIntoJSON(aa);
    

提交回复
热议问题