Accessing Nested Object Properties Using Dot Notation Strings in JavaScript
When manipulating objects, it's often necessary to access deeply nested properties. While dot notation and bracket notation can achieve this, they require specifying each level of nesting individually. This can become tedious and error-prone for complex objects.
A practical solution is to utilize a dot notation string to access child object properties directly. Imagine an object with the following structure:
const r = { a: 1, b: { b1: 11, b2: 99 } };
To access the value 99 using dot notation, you would typically write:
r.b.b2;
However, what if you want to dynamically access the property using a variable string, such as:
const s = "b.b2";
In this scenario, straightforward dot notation (e.g., r.s) or bracket notation (r[s]) won't work.
Custom Function for Property Retrieval
One approach is to create a custom function to split the string by the dot character and iteratively access the properties:
function getDescendantProp(obj, desc) { const arr = desc.split("."); while (arr.length && (obj = obj[arr.shift()])); return obj; } console.log(getDescendantProp(r, "b.b2")); // 99
This function simplifies access to nested properties using a string representation. You can also extend it to handle array index access by modifying the split character accordingly.
The above is the detailed content of How Can I Access Nested JavaScript Object Properties Using a Dot Notation String?. For more information, please follow other related articles on the PHP Chinese website!