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

How to Efficiently Access Nested JavaScript Object Properties Using Dot Notation Strings?

Susan Sarandon
Release: 2024-11-30 10:02:11
Original
631 people have browsed it

How to Efficiently Access Nested JavaScript Object Properties Using Dot Notation Strings?

Accessing Object Child Properties with Dot Notation Strings

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

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.

A Naive but Efficient Solution

function getDescendantProp(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}
Copy after login

This function iteratively splits the string on dots and navigates the object structure, ultimately returning the requested property.

Example Usage

console.log(getDescendantProp(r, "b.b2"));
//-> 99
Copy after login

Extensions

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

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!

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