Problem:
Seeking a function that retrieves values from deeply nested objects by traversing a string path representing the nested structure. For instance:
<code class="javascript">var obj = { foo: { bar: 'baz' } }; // Retrieve obj.foo.bar's value with the string "foo.bar" getValue(obj, "foo.bar");</code>
Solution:
The following solution effectively navigates nested objects using the provided string path:
<code class="javascript">function getValue(obj, path) { var pathParts = path.split('.'); for (var i = 0; i < pathParts.length; i++) { obj = obj[pathParts[i]]; } return obj; }</code>
Explanation:
Example:
<code class="javascript">var obj = { foo: { bar: 'baz' } }; console.log(getValue(obj, "foo.bar")); // Output: "baz"</code>
The above is the detailed content of How to Retrieve Values from Deeply Nested Objects Using String Paths?. For more information, please follow other related articles on the PHP Chinese website!