Introduction
In this lab, we will explore how to get nested values in JavaScript objects using a function called dig. This function can be used to retrieve a specific value from a complex nested object, making it easier to access the necessary information. Through this lab, you will learn how to use the in operator and the reduce() method to traverse through nested objects and find the target value.
How to Get a Nested Value in a JSON Object
To retrieve a target value from a nested JSON object based on a given key, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Check if the
targetexists in theobjusing theinoperator. - If the
targetis found, return the corresponding value in theobj. - If the
targetis not found, useObject.values()andArray.prototype.reduce()to recursively call thedigfunction on each nested object until the first matching key/value pair is found.
Here is the code for the dig function:
const dig = (obj, target) =>
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (typeof val === "object") return dig(val, target);
}, undefined);
To use the dig function, first create a JSON object with nested levels, like this:
const data = {
level1: {
level2: {
level3: "some data"
}
}
};
Then, call the dig function with the JSON object and the desired key:
dig(data, "level3"); // 'some data'
dig(data, "level4"); // undefined
These examples will return the value of the level3 key in the data object and undefined for the non-existent level4 key.
Summary
Congratulations! You have completed the Get Nested Value in Object lab. You can practice more labs in LabEx to improve your skills.