Home  >  Article  >  Web Front-end  >  How to Retrieve Nested Object Values in Javascript Using String Paths?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 07:26:02857browse

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>

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' }
};

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");

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!

Statement:
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