Retrieving Nested Object Values via String Path
Query:
How can a function elegantly extract nested object values by specifying a string path to the desired value?
Goal:
Create a function with the following desired behavior:
var obj = { foo: { bar: 'baz' } }; function(obj, "foo.bar") -> 'baz'
Solution:
To achieve this, consider leveraging the following function:
var deep_value = function(obj, path){ var pathComponents = path.split('.'); for (var i = 0; i < pathComponents.length; i++){ obj = obj[pathComponents[i]]; } return obj; };
This function effectively navigates the object hierarchy, utilizing the string path as a guide, to extract the desired value.
Demonstration:
A demonstration of the function's functionality:
var obj = { foo: { bar: 'baz' } }; console.log(deep_value(obj, "foo.bar")); // Output: 'baz'
Note:
To handle scenarios where the desired value may not exist, the function can be modified to return undefined in such cases.
The above is the detailed content of How to Retrieve Nested Object Values Using String Path Queries?. For more information, please follow other related articles on the PHP Chinese website!