Introduction
In this lab, we will explore the unwind function in JavaScript. The purpose of this function is to produce an array of objects from an object and one of its array-valued properties. By using object destructuring and Array.prototype.map(), we can create an array of objects where each object contains the original object's values, except for the specified key which is mapped to its individual values. Through this lab, we will gain a deeper understanding of how to manipulate and extract data from objects in JavaScript.
Unwind Object Function
To unwind an object by its array-valued property, use the unwind function.
- To get started with coding, open the Terminal/SSH and type
node. - The function uses object destructuring to exclude the key-value pair for the specified
keyfrom the object. - Then, it uses
Array.prototype.map()for the values of the givenkeyto create an array of objects. - Each object contains the original object's values, except for
keywhich is mapped to its individual values.
const unwind = (key, obj) => {
const { [key]: _, ...rest } = obj;
return obj[key].map((val) => ({ ...rest, [key]: val }));
};
Example usage:
unwind("b", { a: true, b: [1, 2] }); // [{ a: true, b: 1 }, { a: true, b: 2 }]
Summary
Congratulations! You have completed the Unwind Object lab. You can practice more labs in LabEx to improve your skills.