Home >Web Front-end >JS Tutorial >How to Retrieve Values from Deeply Nested Objects Using String Paths?

How to Retrieve Values from Deeply Nested Objects Using String Paths?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 23:30:30302browse

How to Retrieve Values from Deeply Nested Objects Using String Paths?

Retrieving Deeply Nested Object Values with a String Path

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:

  1. The string path is split into an array of object keys (in our example, ["foo", "bar"]).
  2. We iterate through the array, retrieving the value associated with each key.
  3. The final result represents the value at the provided path.

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!

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