Introduction
In this lab, we will explore the concept of creating a generator function that walks through all the keys of a given object using recursion. The purpose of this lab is to provide a hands-on experience for learners to understand how to use yield and yield* expressions in combination with for...of loops and Object.keys() to iterate over object keys and their values. By the end of this lab, learners will have a practical understanding of how to recursively walk through an object and generate an array of keys representing the current path and the corresponding values.
Code Walk Through Object Keys
To generate a list of all the keys of a given object, use the following steps:
Open the Terminal/SSH and type
nodeto start practicing coding.Define a generator function called
walkthat takes an object and an array of keys. Use recursion to walk through all the keys of the object.Inside the
walkfunction, use afor...ofloop andObject.keys()to iterate over the keys of the object.Use
typeofto check if each value in the given object is itself an object. If the value is an object, use theyield*expression to recursively delegate to the same generator function,walk, appending the currentkeyto the array of keys.Otherwise,
yieldan array of keys representing the current path and the value of the givenkey.Use the
yield*expression to delegate to thewalkgenerator function.
Here's the code:
const walkThrough = function* (obj) {
const walk = function* (x, previous = []) {
for (let key of Object.keys(x)) {
if (typeof x[key] === "object") yield* walk(x[key], [...previous, key]);
else yield [[...previous, key], x[key]];
}
};
yield* walk(obj);
};
To test the code, create an object and use the walkThrough function to generate a list of all its keys:
const obj = {
a: 10,
b: 20,
c: {
d: 10,
e: 20,
f: [30, 40]
},
g: [
{
h: 10,
i: 20
},
{
j: 30
},
40
]
};
[...walkThrough(obj)];
/*
[
[['a'], 10],
[['b'], 20],
[['c', 'd'], 10],
[['c', 'e'], 20],
[['c', 'f', '0'], 30],
[['c', 'f', '1'], 40],
[['g', '0', 'h'], 10],
[['g', '0', 'i'], 20],
[['g', '1', 'j'], 30],
[['g', '2'], 40]
]
*/
Summary
Congratulations! You have completed the Walk Through Object lab. You can practice more labs in LabEx to improve your skills.