Convert javascript dot notation object to nested object

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

    You could split the key string as path and reduce it for assigning the value by using a default object for unvisited levels.

    function setValue(object, path, value) {
        var keys = path.split('.'),
            last = keys.pop();
    
        keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
        return object;
    }
    
    var source = { 'ab.cd.e': 'foo', 'ab.cd.f': 'bar', 'ab.g': 'foo2' },
        target = Object
            .entries(source)
            .reduce((o, [k, v]) => setValue(o, k, v), {});
    
    console.log(target);

提交回复
热议问题