Convert javascript dot notation object to nested object { 'ab.cd.e' : 'foo', 'ab.cd.f' : 'bar', 'ab.g' : 'foo2' }

PHOTO EMBED

Tue Jul 06 2021 15:35:29 GMT+0000 (Coordinated Universal Time)

Saved by [deleted user] #javascript

//expected result {ab: {cd: {e:'foo', f:'bar'}, g:'foo2'}}

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'
}));
content_copyCOPY

https://stackoverflow.com/questions/7793811/convert-javascript-dot-notation-object-to-nested-object