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

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

Patricia Arquette
Release: 2024-11-28 22:04:11
Original
853 people have browsed it

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

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

To access the value 99 using dot notation, you would typically write:

r.b.b2;
Copy after login

However, what if you want to dynamically access the property using a variable string, such as:

const s = "b.b2";
Copy after login

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

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!

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