Skip to content

JavaScript dot notation to object | Example code

  • by

If you have a string in dot notation, then use the concept of split(‘.’) along with a map() to convert dot notation to an object in JavaScript.

JavaScript dot notation to an object

A simple example code turns a string in dot notation into a nested object with a value.

<!DOCTYPE html>
<html>
<body>

  <script type="text/javascript">
    const keys = "details1.details2.details3.details4.details5"
    const firsName = "David";
    var tempObject = {};
    var container = tempObject;
    keys.split('.').map((k, i, values) => {
     container = (container[k] = (i == values.length - 1 ? firsName : {}))
   });
    console.log(JSON.stringify(tempObject, null, ' '));
  </script>

</body>
</html>

Output:

JavaScript dot notation to object

Convert a complex JavaScript object to a dot notation object

You can recursively add the properties to a new object, and then convert it to JSON:

 <script type="text/javascript">
    var obj = { "status": "success", "auth": { "code": "23123213", "name": "qwerty asdfgh" } };

    var res = {};
    (function recurse(obj, current) {
      for(var key in obj) {
        var value = obj[key];
        var newKey = (current ? current + "." + key : key); 
        if(value && typeof value === "object") {
          recurse(value, newKey);  
        } else {
          res[newKey] = value;  
        }
      }
    })(obj);
    var result = JSON.stringify(res);  

    console.log(result)

</script>

Output:

{“status”:”success”,”auth.code”:”23123213″,”auth.name”:”qwerty asdfgh”}

Convert JavaScript dot notation object to nested object

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

Output:


{
  "ab": {
    "cd": {
      "e": "foo",
      "f": "bar"
    },
    "g": "foo2"
  }
}

Do comment if you have any doubts or suggestions on this JS notation topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading