Home >Web Front-end >JS Tutorial >How can I Access Deeply Nested Object Values Using a String Path?
Accessing deeply nested object properties can be cumbersome, especially when using string paths to traverse the object. This question seeks a solution to retrieve values from objects based on a provided string path.
The suggested approach employs the following function, deep_value, which iteratively navigates the object properties specified in the path string:
<code class="javascript">var deep_value = function(obj, path) { for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) { obj = obj[path[i]]; } return obj; };</code>
Consider the following object:
var obj = { foo: { bar: 'baz' } };
To access the value of obj.foo.bar using the string path "foo.bar", the deep_value function can be invoked as follows:
deep_value(obj, "foo.bar"); // returns "baz"
The above is the detailed content of How can I Access Deeply Nested Object Values Using a String Path?. For more information, please follow other related articles on the PHP Chinese website!