In JavaScript, an array represents a collection of items, whereas an object represents a collection of key-value pairs. There are situations where converting an array into an object can enhance the ease of accessing specific items within it. There are several ways to convert arrays into objects, depending on your specific requirements and the structure you want for the resulting object In this article, we'll explore various methods for converting an array to an object in javascript.
Table of Contents
1. Using a For Loop:
Iterate the array of elements and manually create key-value pairs to construct an object. This approach gives you full control over the object's structure.
Example:-
2. Using the reduce Method:
The reduce method allows you to accumulate values from an array into a single object. You can define a callback function that transforms each array element into a key-value pair.
Example1:-
Example2:-
If an array contains 2-element arrays where first element is the key and second element is the value. So you can easily convert the array to object using reduce.
Output:
3. Using the Object.fromEntries() method
You can use the Object.fromEntries() method to create an object from an array of key-value pairs
Example:
Output
4. Using the Object.assign() method
You can use the Object.assign() method to create a new object by merging the properties of an array into an empty object.
Example:
Output
Note: Choose the method that fulfil your needs based on the input data and the required output format. The Object.fromEntries method is especially handy when you have an array of key-value pairs and want to convert it into an object.
Here is the stack-overflow link to see more answers on this
0 Comments