Home > Web Front-end > JS Tutorial > How to Access Nested JavaScript Objects and Arrays Using String Paths?

How to Access Nested JavaScript Objects and Arrays Using String Paths?

Susan Sarandon
Release: 2024-12-26 14:22:16
Original
166 people have browsed it

How to Access Nested JavaScript Objects and Arrays Using String Paths?

Accessing JavaScript Objects and Arrays by String Path

In certain scenarios, developers often encounter data structures with complex nesting and face the challenge of accessing specific values within them using strings as paths.

For instance, consider the following object:

var someObject = {
    'part1': {
        'name': 'Part 1',
        'size': '20',
        'qty': '50'
    },
    'part2': {
        'name': 'Part 2',
        'size': '15',
        'qty': '60'
    },
    'part3': [
        {
            'name': 'Part 3A',
            'size': '10',
            'qty': '20'
        },
        {
            'name': 'Part 3B',
            'size': '5',
            'qty': '20'
        },
        {
            'name': 'Part 3C',
            'size': '7.5',
            'qty': '20'
        }
    ]
};
Copy after login

To retrieve nested values using string paths, the following techniques can be employed:

Pure JavaScript

Using the Object.byString utility function, you can traverse the object and access specific values:

Object.byString = function(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
};
Copy after login

Usage:

Object.byString(someObject, 'part3[0].name'); // "Part 3A"
Copy after login

jQuery

jQuery's $.val() method can also be used to navigate nested objects and arrays:

$.val('part1.name', someObject); // "Part 1"
$.val('part2.qty', someObject); // 60
$.val('part3[0].name', someObject); // "Part 3A"
Copy after login

Both approaches provide convenient ways to access data within nested structures by string paths, simplifying the handling and manipulation of complex data.

The above is the detailed content of How to Access Nested JavaScript Objects and Arrays Using String Paths?. 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