Convert javascript dot notation object to nested object

后端 未结 7 1198
我在风中等你
我在风中等你 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:50

    Function name is terrible and the code was quickly made, but it should work. Note that this modifies the original object, I am not sure if you wanted to create a new object that is expanded version of the old one.

    (function(){
    
        function parseDotNotation( str, val, obj ){
        var currentObj = obj,
            keys = str.split("."), i, l = keys.length - 1, key;
    
            for( i = 0; i < l; ++i ) {
            key = keys[i];
            currentObj[key] = currentObj[key] || {};
            currentObj = currentObj[key];
            }
    
        currentObj[keys[i]] = val;
        delete obj[str];
        }
    
        Object.expand = function( obj ) {
    
            for( var key in obj ) {
            parseDotNotation( key, obj[key], obj );
            }
        return obj;
        };
    
    })();
    
    
    
    var expanded = Object.expand({
        'ab.cd.e' : 'foo',
            'ab.cd.f' : 'bar',
        'ab.g' : 'foo2'
    });
    
    
    
    JSON.stringify( expanded );  
    
    
    //"{"ab":{"cd":{"e":"foo","f":"bar"},"g":"foo2"}}"
    
    0 讨论(0)
提交回复
热议问题