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
Susan SarandonOriginal
2024-11-30 10:02:11667browse

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}};

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;
}

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

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;
}

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!

Statement:
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