Home > Web Front-end > JS Tutorial > How Can I Access Nested JavaScript Object Properties Using Dot Notation Strings?

How Can I Access Nested JavaScript Object Properties Using Dot Notation Strings?

Mary-Kate Olsen
Release: 2024-11-21 14:54:13
Original
561 people have browsed it

How Can I Access Nested JavaScript Object Properties Using Dot Notation Strings?

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;
}
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template