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

How Can I Safely Convert a JavaScript Dot Notation String to an Object Reference?

Linda Hamilton
Release: 2024-12-20 19:27:10
Original
246 people have browsed it

How Can I Safely Convert a JavaScript Dot Notation String to an Object Reference?

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

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

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!

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