Introduction
In this lab, we will explore how to use the deepMapKeys function in JavaScript to map an object's keys recursively. We will learn how to create a new object with the same values and mapped keys using a provided function for each key. Through hands-on exercises and examples, we will understand how this function works and how it can be used in practical scenarios.
Deep Map Object Keys
To deep map an object's keys, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
deepMapKeysfunction with the provided object and a function that generates new keys. - The function creates an object with the same values as the provided object and keys generated by running the provided function for each key.
- Iterate over the object's keys using
Object.keys(). - Create a new object with the same values and mapped keys using
Array.prototype.reduce()and the provided function. - If a value is an object, recursively call
deepMapKeyson it to map its keys as well.
const deepMapKeys = (obj, fn) =>
Array.isArray(obj)
? obj.map((val) => deepMapKeys(val, fn))
: typeof obj === "object"
? Object.keys(obj).reduce((acc, current) => {
const key = fn(current);
const val = obj[current];
acc[key] =
val !== null && typeof val === "object"
? deepMapKeys(val, fn)
: val;
return acc;
}, {})
: obj;
Here's an example usage of deepMapKeys:
const obj = {
foo: "1",
nested: {
child: {
withArray: [
{
grandChild: ["hello"]
}
]
}
}
};
const upperKeysObj = deepMapKeys(obj, (key) => key.toUpperCase());
/*
{
"FOO":"1",
"NESTED":{
"CHILD":{
"WITHARRAY":[
{
"GRANDCHILD":[ 'hello' ]
}
]
}
}
}
*/
Summary
Congratulations! You have completed the Deep Map Object Keys lab. You can practice more labs in LabEx to improve your skills.