How to Convert a JavaScript String in Dot Notation into an Object Reference
Using a straightforward and elegant one-liner, it's possible to convert a JavaScript string in dot notation to an object reference. Here's how:
'a.b.etc'.split('.').reduce(index, obj)
where index is a function used for indexing.
Splitting the String into an Array
Before performing the conversion, the dot-notation string is split into an array using the split('.') method. For instance, the string 'a.b.etc' would be split into ['a', 'b', 'etc'].
Using the reduce Method for Indexing
The reduce method is used to iterate over the array and index into the object. The accumulator, o, represents the current object being indexed, and i is the current element in the array. The index function is applied to each element, where it returns o[i], the value indexed into the current object.
Putting It All Together
Combining the string splitting and indexing operations, we get the following:
'a.b.etc'.split('.').reduce(function(o, i) { return o[i] }, obj)
This will return the nested value, obj.a.b.etc, from the original object reference.
Note: There are alternative methods, but this one-liner offers elegance and simplicity.
The above is the detailed content of How to Convert a Dot Notation String to an Object Reference in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!