Introduction
In this lab, we will explore how to map an object array to an object using the provided mapping functions. We will use the Array.prototype.reduce() method to map the array, and the mapKey and mapValue functions to map the keys and values of the resulting object respectively. By the end of this lab, you will have a better understanding of how to transform data structures in JavaScript.
How to Map an Array to an Object in JavaScript
To map an object array to an object in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.reduce()to map the array to an object. - Use the
mapKeyparameter to map the keys of the object and themapValueparameter to map the values.
Here's an example code snippet that demonstrates how to use the objectify function to map an object array to an object:
const objectify = (arr, mapKey, mapValue = (i) => i) =>
arr.reduce((acc, item) => {
acc[mapKey(item)] = mapValue(item);
return acc;
}, {});
You can then use the objectify function to map an object array to an object in the following ways:
const people = [
{ name: "John", age: 42 },
{ name: "Adam", age: 39 }
];
// Map the object array to an object using the name property as keys
objectify(people, (p) => p.name.toLowerCase());
// Output: { john: { name: 'John', age: 42 }, adam: { name: 'Adam', age: 39 } }
// Map the object array to an object using the name property as keys and the age property as values
objectify(
people,
(p) => p.name.toLowerCase(),
(p) => p.age
);
// Output: { john: 42, adam: 39 }
Summary
Congratulations! You have completed the Map an Array to an Object lab. You can practice more labs in LabEx to improve your skills.