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
Release: 2024-10-24 23:30:30
Original
335 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template