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.
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:
- Use
Array.prototype.map()to iterate through each selector, and applyString.prototype.replace()to replace square brackets with dots. - Use
String.prototype.split()to split each selector into an array of strings. - Use
Array.prototype.filter()to remove any empty values. - 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.