Introduction
In this lab, we will explore a JavaScript function that flattens an object with the paths for keys. The function uses recursion and Object.keys() combined with Array.prototype.reduce() to convert every leaf node to a flattened path node. By the end of this lab, you will have a better understanding of how to manipulate JavaScript objects and flatten them for easier data processing.
This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.
Flattening an Object
To flatten an object with paths for keys, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use recursion to flatten the object.
- Use
Object.keys()combined withArray.prototype.reduce()to convert every leaf node to a flattened path node. - If the value of a key is an object, call the function recursively with the appropriate
prefixto create the path usingObject.assign(). - Otherwise, add the appropriate prefixed key-value pair to the accumulator object.
- Omit the second argument,
prefix, unless you want every key to have a prefix.
Here is an example implementation:
const flattenObject = (obj, prefix = "") =>
Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? `${prefix}.` : "";
if (
typeof obj[k] === "object" &&
obj[k] !== null &&
Object.keys(obj[k]).length > 0
) {
Object.assign(acc, flattenObject(obj[k], pre + k));
} else {
acc[pre + k] = obj[k];
}
return acc;
}, {});
You can use the flattenObject function like this:
flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }
Summary
Congratulations! You have completed the Flatten Object lab. You can practice more labs in LabEx to improve your skills.