Accessing Object Child Properties via Dot Notation String
When dealing with nested objects, accessing deeply buried properties can be cumbersome. Determining the ideal way of achieving this using a string dot notation has puzzled numerous developers.
Consider an object defined as follows:
var r = { a: 1, b: { b1: 11, b2: 99 } };
To access the value of b2, you can typically use:
r.b.b2 r['b']['b2']
However, defining a string like var s = "b.b2" and attempting to access r[s] or r.s will fail.
Solution:
One method involves creating a custom function that splits the string on dots and iteratively retrieves the desired property. A simple example is:
function getDescendantProp(obj, desc) { var arr = desc.split("."); while (arr.length && (obj = obj[arr.shift()])); return obj; } console.log(getDescendantProp(r, "b.b2")); // Outputs 99
This function recursively descends the object hierarchy based on the dot-separated path, returning the final value. Notably, it can also handle accessing array indices using dot notation:
console.log(getDescendantProp({ a: [1, 2, 3] }, 'a.2')); // Outputs 3
The above is the detailed content of How to Access Nested Object Properties Using Dot Notation Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!