Home > Web Front-end > JS Tutorial > body text

How can I Access Deeply Nested Object Values Using a String Path?

Patricia Arquette
Release: 2024-10-24 19:24:02
Original
408 people have browsed it

How can I Access Deeply Nested Object Values Using a String Path?

Acquiring Deeply Nested Object Values via 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.

Proposed Solution

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

Breakdown

  • The split('.') operation converts the string path into an array of property names.
  • A loop is used to traverse the object, accessing each property in sequence.
  • The last iteration returns the final nested value.

Example

Consider the following object:

var obj = {
  foo: { bar: 'baz' }
};
Copy after login

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!