Home  >  Article  >  Web Front-end  >  How to Access Nested JavaScript Object Properties Using a String?

How to Access Nested JavaScript Object Properties Using a String?

DDD
DDDOriginal
2024-11-20 15:35:16587browse

How to Access Nested JavaScript Object Properties Using a String?

Accessing Object Child Properties with Dot Notation String

Accessing child properties of JavaScript objects using chained dot notation is a common programming task. However, there are limitations when using this approach for dynamic property access.

Consider the following object:

var r = { a: 1, b: { b1: 11, b2: 99 } };

To access the value of b2, one can utilize standard dot notation:

r.b.b2

However, if one requires dynamic property access based on a string, such as:

var s = "b.b2";

The direct attempts like r.s or r[s] would fail. One solution is to employ a custom function that iterates through the string segments to retrieve the property:

function getDescendantProp(obj, desc) {
  var arr = desc.split(".");
  while (arr.length && (obj = obj[arr.shift()]));
  return obj;
}

console.log(getDescendantProp(r, "b.b2")); // 99
````

This function effectively simulates the behavior of dot notation by breaking down the string and recursively accessing the corresponding properties. However, it is important to note that this method works best for simple object property scenarios. Arrays can also be accessed using this approach by treating elements as dotted properties:

getDescendantProp({ a: [ 1, 2, 3 ] }, 'a.2'); // 3

The above is the detailed content of How to Access Nested JavaScript Object Properties Using a String?. 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