Home > Web Front-end > JS Tutorial > How to Convert a Dot Notation String to an Object Reference in JavaScript?

How to Convert a Dot Notation String to an Object Reference in JavaScript?

Barbara Streisand
Release: 2024-12-17 13:25:13
Original
583 people have browsed it

How to Convert a Dot Notation String to an Object Reference in JavaScript?

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template