Accessing Nested Object Properties with Dot Notation Strings
When working with complex objects, accessing deeply nested properties can be a cumbersome process. Standard JavaScript syntax requires manual navigation through the property hierarchy, which can become tedious and error-prone. This issue has prompted the search for alternative approaches to simplify this task.
One sought-after solution is the ability to access nested properties using a dot notation string. However, this feature is not natively supported in JavaScript. Here's a simple function that allows for this functionality:
function getDescendantProp(obj, desc) { var arr = desc.split("."); while (arr.length && (obj = obj[arr.shift()])); return obj; }
With this function, you can access deeply nested properties using a string:
var r = { a: 1, b: { b1: 11, b2: 99 } }; console.log(getDescendantProp(r, "b.b2")); // 99
Note that this approach can also be used to access array elements by specifying their numerical indexes as part of the dot notation string:
getDescendantProp({ a: [1, 2, 3] }, 'a.2'); // 3
The above is the detailed content of How Can I Access Nested JavaScript Object Properties Using Dot Notation Strings?. For more information, please follow other related articles on the PHP Chinese website!