Convert javascript dot notation object to nested object

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

    I believe this is what you're after:

    function deepen(obj) {
      const result = {};
    
      // For each object path (property key) in the object
      for (const objectPath in obj) {
        // Split path into component parts
        const parts = objectPath.split('.');
    
        // Create sub-objects along path as needed
        let target = result;
        while (parts.length > 1) {
          const part = parts.shift();
          target = target[part] = target[part] || {};
        }
    
        // Set value at end of path
        target[parts[0]] = obj[objectPath]
      }
    
      return result;
    }
    
    // For example ...
    console.log(deepen({
      'ab.cd.e': 'foo',
      'ab.cd.f': 'bar',
      'ab.g': 'foo2'
    }));

提交回复
热议问题