How do I turn a string in dot notation into a nested object with a value – JavaScript?


Let’s say the following is our string in dot notation −

const keys = "details1.details2.details3.details4.details5"

And the following is our array −

const firsName = "David";

To turn into a nested object, use the concept of split(‘.’) along with map().

Example

Following is the code −

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

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo227.js.

Output

The output is as follows −

PS C:\Users\Amit\JavaScript-code> node demo227.js
{
 "details1": {
  "details2": {
   "details3": {
    "details4": {
     "details5": "David"
    }
   }
  }
 }
}

Updated on: 03-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements