Nested JSON Object Value Retrieval

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring how to retrieve nested values from a JSON object based on an array of keys. We will be using the reduce() method to traverse the object's nested structure and retrieve the target value. By the end of this lab, you will have a better understanding of how to access specific values within a complex JSON object.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28264{{"`Nested JSON Object Value Retrieval`"}} javascript/data_types -.-> lab-28264{{"`Nested JSON Object Value Retrieval`"}} javascript/arith_ops -.-> lab-28264{{"`Nested JSON Object Value Retrieval`"}} javascript/comp_ops -.-> lab-28264{{"`Nested JSON Object Value Retrieval`"}} javascript/array_methods -.-> lab-28264{{"`Nested JSON Object Value Retrieval`"}} javascript/higher_funcs -.-> lab-28264{{"`Nested JSON Object Value Retrieval`"}} end

How to Retrieve a Nested Value in an Object Using an Array of Keys

To retrieve a specific value from a nested JSON object, you can use the deepGet function. This function takes in an object and an array of keys, and returns the target value if it exists in the object.

To use the deepGet function:

  • Create an array of the keys you want to retrieve from the nested JSON object.
  • Call the deepGet function with the object and the array of keys.
  • The function will return the target value if it exists, or null if it does not.

Here is the code for the deepGet function:

const deepGet = (obj, keys) =>
  keys.reduce(
    (xs, x) => (xs && xs[x] !== null && xs[x] !== undefined ? xs[x] : null),
    obj
  );

And here is an example of how to use the deepGet function:

let index = 2;
const data = {
  foo: {
    foz: [1, 2, 3],
    bar: {
      baz: ["a", "b", "c"]
    }
  }
};
deepGet(data, ["foo", "foz", index]); // returns 3
deepGet(data, ["foo", "bar", "baz", 8, "foz"]); // returns null

To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Get Nested Value in Object Based on Array of Keys lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like