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

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

Mary-Kate Olsen
Release: 2024-12-22 08:32:10
Original
743 people have browsed it

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

Converting a JavaScript String in Dot Notation into an Object Reference

Understanding the Need

Given a JavaScript string that represents a property path in an object using dot notation (e.g., "a.b"), the goal is to convert this string into an actual reference to the desired property within the object.

The Evaluation Method

One straightforward method to accomplish this conversion is to use the eval() function. While using eval() is generally discouraged for security reasons, it is applicable in this specific scenario because the input string is controlled and expected to adhere to a specific syntax. The code would simply use eval("obj" string) to obtain the desired property reference.

A String-to-Array-to-Object Conversion

An alternative, less concise but potentially more efficient and robust approach involves converting the dot-notation string into an array of key names (e.g., ["a", "b"]) and subsequently using this array as a reference path:

const keyArray = dotNotationString.split('.');
const value = obj[keyArray[0]][keyArray[1]];
Copy after login

Recursive Function Implementation

A third option is to create a recursive function that navigates the object using the input string:

function getPropertyByDotNotation(obj, string) {
  if (!obj) {
    return undefined;
  }
  if (!string || string.length === 0) {
    return obj;
  }
  const [key, ...rest] = string.split('.');
  return getPropertyByDotNotation(obj[key], rest.join('.'));
}
Copy after login

This recursive approach provides flexibility and handles objects of arbitrary depth.

Conclusion

The choice of method depends on specific requirements and performance considerations. When working with trusted input and targeting simplicity, eval() can be suitable. For scenarios with performance concerns or more complex input validation, the array or recursive approaches offer reliable alternatives.

The above is the detailed content of How Can I Convert a JavaScript Dot Notation String into 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