Home > Web Front-end > JS Tutorial > body text

How to Retrieve Nested Object Values in Javascript Using String Paths?

Mary-Kate Olsen
Release: 2024-10-25 07:26:02
Original
856 people have browsed it

How to Retrieve Nested Object Values in Javascript Using String Paths?

Nested Object Value Retrieval in Javascript Using String Path

Introduction:

Retrieving values from deeply nested objects can be a cumbersome task. In this question, a user seeks a Javascript function that efficiently extracts values by traversing the object using a provided string path.

Deep Value Retrieval Function:

The provided solution satisfies this requirement with a function named deep_value():

<code class="javascript">function deep_value(obj, path) {
  for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) {
    obj = obj[path[i]];
  }
  return obj;
}</code>
Copy after login

This function accepts two parameters:

  • obj: The target object from which the value will be retrieved.
  • path: A string specifying the path to the desired value, separated by dots (.) for nested keys.

Function Workflow:

The function iterates through the string path by splitting it into an array of keys. It then traverses the object, assigning the previous value to obj at each key. This allows the function to navigate through the nested structure of the object. Finally, it returns the value corresponding to the last key in the provided path.

Usage Example:

To illustrate the usage, consider the following object:

var obj = {
  foo: { bar: 'baz' }
};
Copy after login

To access the value of obj.foo.bar using the provided string path, you can use the following code:

result = deep_value(obj, "foo.bar");
Copy after login

The result variable will now hold the value 'baz' as expected. This function provides a convenient and versatile的方式 to retrieve nested values from complex objects in Javascript.

The above is the detailed content of How to Retrieve Nested Object Values in Javascript Using String Paths?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!