Converting a JavaScript Dot Notation String into an Object Reference
In JavaScript, you can encounter scenarios where you need to convert a dot notation string, such as "a.b", into a reference to a nested property within an object. This can be particularly useful when working with complex data structures or data coming from external sources.
One straightforward solution is to use the eval() function:
var obj = { a: { b: '1', c: '2' } }; eval('var val = obj.a.b'); console.log(val); // '1'
However, using eval() is generally discouraged due to security concerns and potential performance issues.
A more reliable approach is to utilize index-based accessing using a combination of split and reduce:
function index(obj, path) { return path.split('.').reduce((o, i) => o[i], obj); } var val = index(obj, 'a.b'); console.log(val); // '1'
This function effectively splits the path at each dot ('.') and uses reduce to iteratively access nested properties within the object.
By utilizing this technique, you can safely and efficiently convert dot notation strings into object references.
The above is the detailed content of How Can I Safely Convert a JavaScript Dot Notation String to an Object Reference?. For more information, please follow other related articles on the PHP Chinese website!