Transform string with dot notation to a nested object

Let's assume that you have the following string:

let string = 'engineers.erik.age';

If you want to add properties dynamically to an object (transform dot notation to a nested object), the result that you want to get is:

let object = {
    "engineers": {
        "erik": {
            "age": 30

To go from the string to the object:

// Defining properties as string with dot notation
let string = 'engineers.erik.age';

// Transforming string into array of props
let props = string.split('.');

// Getting the last element of the array
let last = props.pop();

// Defining object and reference to the object
let object = ref = {};

// Declare new object for every prop and get reference to that prop
props.forEach(prop => {
    ref[prop] = {};
    ref = ref[prop];

// Assign last value 
ref[last] = 30;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.