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

How to Retrieve Nested Object Values Using String Path Queries?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 05:21:02453browse

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'

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

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'

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!

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