Home  >  Article  >  Web Front-end  >  How can I Access Deeply Nested Object Values Using a String Path?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 19:24:02409browse

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>

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' }
};

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!

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