Get Nested Object Property From Path String

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to retrieve nested object properties using a given path string in JavaScript. We will learn how to use various array methods such as map(), filter(), and reduce() to extract specific values from complex objects. This skill is essential for working with large datasets and APIs that return nested JSON objects.


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`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28356{{"`Get Nested Object Property From Path String`"}} javascript/data_types -.-> lab-28356{{"`Get Nested Object Property From Path String`"}} javascript/arith_ops -.-> lab-28356{{"`Get Nested Object Property From Path String`"}} javascript/comp_ops -.-> lab-28356{{"`Get Nested Object Property From Path String`"}} javascript/array_methods -.-> lab-28356{{"`Get Nested Object Property From Path String`"}} javascript/higher_funcs -.-> lab-28356{{"`Get Nested Object Property From Path String`"}} javascript/spread_rest -.-> lab-28356{{"`Get Nested Object Property From Path String`"}} end

How to Retrieve Nested Object Properties from Path Strings

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

The following function retrieves a set of properties from an object by using selectors specified in a path string. To achieve this, follow these steps:

  1. Use Array.prototype.map() to iterate through each selector, and apply String.prototype.replace() to replace square brackets with dots.
  2. Use String.prototype.split() to split each selector into an array of strings.
  3. Use Array.prototype.filter() to remove any empty values.
  4. Use Array.prototype.reduce() to retrieve the value indicated by each selector.

Here is the function:

const get = (from, ...selectors) =>
  [...selectors].map((s) =>
    s
      .replace(/\[([^\[\]]*)\]/g, ".$1.")
      .split(".")
      .filter((t) => t !== "")
      .reduce((prev, cur) => prev && prev[cur], from)
  );

You can use this function to retrieve values from a nested object using a path string. Here is an example:

const obj = {
  selector: { to: { val: "val to select" } },
  target: [1, 2, { a: "test" }]
};
get(obj, "selector.to.val", "target[0]", "target[2].a");
// ['val to select', 1, 'test']

Summary

Congratulations! You have completed the Get Nested Object Property From Path String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like