Home > Web Front-end > JS Tutorial > How to Retrieve Nested Object Values Using String Path Queries?

How to Retrieve Nested Object Values Using String Path Queries?

Patricia Arquette
Release: 2024-10-25 05:21:02
Original
555 people have browsed it

How to Retrieve Nested Object Values Using String Path Queries?

Retrieving Nested Object Values via String Path

Query:

How can a function elegantly extract nested object values by specifying a string path to the desired value?

Goal:

Create a function with the following desired behavior:

var obj = { foo: { bar: 'baz' } };
function(obj, "foo.bar") -> 'baz'
Copy after login

Solution:

To achieve this, consider leveraging the following function:

var deep_value = function(obj, path){
    var pathComponents = path.split('.');
    for (var i = 0; i < pathComponents.length; i++){
        obj = obj[pathComponents[i]];
    }
    return obj;
};
Copy after login

This function effectively navigates the object hierarchy, utilizing the string path as a guide, to extract the desired value.

Demonstration:

A demonstration of the function's functionality:

var obj = { foo: { bar: 'baz' } };
console.log(deep_value(obj, "foo.bar")); // Output: 'baz'
Copy after login

Note:

To handle scenarios where the desired value may not exist, the function can be modified to return undefined in such cases.

The above is the detailed content of How to Retrieve Nested Object Values Using String Path Queries?. 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