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