In JavaScript, there are multiple ways to access object properties. However, accessing nested properties with a string path can be a challenge.
Given an object like:
var r = { a:1, b: { b1:11, b2: 99}};
Consider a scenario where you want to access the value 99 by specifying a path string var s = "b.b2". While the traditional methods like r.b.b2 or r['b']['b2'] work, you may prefer to use a more concise notation.
function getDescendantProp(obj, desc) { var arr = desc.split("."); while(arr.length && (obj = obj[arr.shift()])); return obj; }
This function iteratively splits the string on dots and navigates the object structure, ultimately returning the requested property.
console.log(getDescendantProp(r, "b.b2")); //-> 99
The provided function only supports accessing nested object properties. For more advanced usage, you could modify it to handle array indexes as well:
function advancedGetDescendantProp(obj, desc) { var arr = desc.split("."); while(arr.length) { let key = arr.shift(); if (isNaN(key)) { obj = obj[key]; } else { obj = obj[parseInt(key)]; } if (!obj) return undefined; } return obj; }
The above is the detailed content of How to Efficiently Access Nested JavaScript Object Properties Using Dot Notation Strings?. For more information, please follow other related articles on the PHP Chinese website!