Transform a dot notation string into an object reference in JavaScript

I’m working with a JavaScript object defined as follows:

let myObject = { x: { y: '10', z: '20' } };

and I have a string:

"x.y"

What is the best way to convert this string into a reference so that I can access its value like this:

let value = myObject.x.y;

If the string were simply ‘x’, I could use myObject[x]. However, this case is more complicated. I’m sure there’s a simple solution, but I can’t seem to find it right now.

One approach is to split the string by the dot and then iterate over the split array to traverse the object step-by-step. Here’s a simple way to achieve this:

let myObject = { x: { y: '10', z: '20' } };
let str = "x.y";

let parts = str.split('.');
let value = parts.reduce((acc, part) => acc && acc[part], myObject);
console.log(value);  // Outputs: '10'

By using reduce, you can progressively get deeper into the object with each part of the key. This method is quite reliable for nested objects and safely handles any undefined references along the path.