In order to design interactive and dynamic user interfaces for websites, a lot of programmers employ JavaScript. The object is one of JavaScript’s primary data types for storing key-value pairs. In contrast, arrays are used to hold elements in a specific order.
You might occasionally need to change an array into an object so you can manipulate or access the data differently.This conversion can be done easily using a few built-in JavaScript methods.
Let’s dive!
Why Is There A Need to convert array to object in javascript
How to convert an array to an object in javascript is required for a variety of reasons. Among the primary reasons are:
- To access array elements using keys: Arrays are accessed using numerical indices, but if you need to access array elements using keys instead, converting the array to an object can make this easier.
- To use object methods: You must first transform an array into an object if you want to utilize built-in object methods.
- To group array elements: Converting the array to an object can make this grouping easier, as you can use the key as the object property and add the corresponding objects to an array.
- To remove duplicates: By converting an array to an object, duplicate values can be removed.
Approaches to convert array to object in JavaScript
There are three methods, how to convert an array to an object
in javascript. Methods are listed below:-
- Using a for loop to iterate over the array
- Using the Array.reduce() method
- Using the Object.fromEntries() method
Let’s have a look.
1. Using a for loop to iterate over the array
We can make an object by iterating over an array. Let’s see!
Source Code:-
const arr = ['apple', 'banana', 'cherry'];
const obj = {};
for (let i = 0; i < arr.length; i++) {
obj[i] = arr[i];
}
console.log(obj);
Output:-
{
0: "apple",
1: "banana",
2: "cherry"
}
Explanation of code:-
- We create an empty object obj.
- A loop is used to iterate over the array to extract the data.
- Each arr element is assigned to the object obj with a key that corresponds to its index inside the loop.
- We log the resulting object to the console.
2. Using the Array.reduce() method
With the help of Array.reduce() potent tool, you may conduct intricate operations on an array and get a single result back. During each iteration of the array, the method applies a callback function to each element and builds up a result.
Source Code:-
const arr = ['Potato', 'Burger', 'Chess'];
//here we are using the function
const obj = arr.reduce((acc, cur, i) => {
acc[i] = cur;
return acc;
}, {});
console.log(obj);
Output:-
{ '0': 'Potato', '1': 'Burger', '2': 'Chess' }
Explanation of code:-
- We use the reduce() to iterate over an arr.
- For each entry of the arr, a fresh key-value pair is made and then added to the accumulator object. The key is the index of the element in the arr, and the value is the actual element.
- We log the resulting object to the console.
3. Using the Object.fromEntries() method
A key-value pair array is used to build an object using the Object.fromEntries() function. It takes an iterable object as a parameter and creates a new object with key-value pair properties.
Sample Code:-
const arr = [['name', 'Jyoti'], ['age', 18], ['city', 'Garhwa']];
//here we are using the function
const obj = Object.fromEntries(arr);
console.log(obj);
Output:-
{ name: 'Jyoti', age: 18, city: 'Garhwa' }
Explanation of code:-
- A key-value pair is contained in each inner array of the arr of arrays that we generate.
- Using the Object.fromEntries() function, a new object is created from the arr of key-value pairs.
- The function takes an iterable with key-value pairs as elements and returns a new object with properties corresponding to those keys and values.
- The outcome object is recorded to the console.
Best approach:- Using the Object.fromEntries() method
If we were to choose the best approach among them, I would recommend using the Object.fromEntries(). Some reasons are:-
- Concise and readable code: Using the Object.fromEntries() method allows you to convert the array to an object in a single line of code, which makes it more concise and easier to read and understand.
- Works for any array of key-value pairs: Object.fromEntries() can be used with any array of key-value pairs, unlike the rest methods, which are restricted to arrays having a specific structure.
- No need to create an empty object: You must first build an empty object in the first two methods before adding key-value pairs to it. The Object.fromEntries() function can be used to create the object directly from the array of key-value pairs, which simplifies the code.
- Better performance: Object.fromEntries() is designed specifically for building objects from arrays of key-value pairs and is expected to perform more quickly than the other methods.
Overall, Object.fromEntries() is the simplest, most adaptable, and effective way to turn an array into an object.
Sample Problem how to convert array to object in JavaScript
Sample Problem 1:- Using a for loop to iterate over the array
Problem statement:- Samaira wants to determine the overall sales for each product category and she has a set of numbers that reflect the sales figures for a variety of products. How will she do.
Solution:-
Solution Code:-
const salesFigures = [100, 50, 75, 200, 150, 300, 100, 50];
const categories = ['category1', 'category2', 'category1', 'category3', 'category2', 'category3', 'category1', 'category2'];
const salesByCategory = {};
for (let i = 0; i < salesFigures.length; i++) {
const category = categories[i];
const sales = salesFigures[i];
if (salesByCategory[category]) {
salesByCategory[category] += sales;
} else {
salesByCategory[category] = sales;
}
}
console.log(salesByCategory);
Output:-
{ category1: 275, category2: 250, category3: 500 }
Explanation:-
- We have an array salesFigures that contains the sales figures for each product.
- We have an array of categories that contains the category for each product.
- We create an empty object salesByCategory.
- We use a for loop to iterate over the sales figures array.
- For each iteration, we get the category and sales figures for the current product.
- We check if the category already exists as a property in the salesByCategory object.
- If it does, we add the current sales figures to the existing value.
- If it doesn’t, we create a new property with the category as the key and the current sales figures as the value.
- We log the resulting object to the console.
Sample Problem 2:- Using the Array.reduce() method
Problem statement:- Imagine you want to determine the total sales for each product category and you have an array of objects containing the sales numbers for a collection of products.
Solution Code:-
const sales = [
{ category: 'category1', sales: 100 },
{ category: 'category2', sales: 50 },
{ category: 'category1', sales: 75 },
{ category: 'category3', sales: 200 },
{ category: 'category2', sales: 150 },
{ category: 'category3', sales: 300 },
{ category: 'category1', sales: 100 },
{ category: 'category2', sales: 50 }
];
const salesByCategory = sales.reduce((acc, cur) => {
const category = cur.category;
const sales = cur.sales;
if (acc[category]) {
acc[category] += sales;
} else {
acc[category] = sales;
}
return acc;
}, {});
console.log(salesByCategory);
Output:-
{ category1: 275, category2: 250, category3: 500 }
Explanation:-
- We have an array sales that contains objects representing the sales figures for each product.
- We use the reduce() method to iterate over the sales array.
- For each object in the array, we get the category and sales figures.
- We check if the category already exists as a property in the accumulator object.
- If it does, we add the current sales figures to the existing value.
- If it doesn’t, we create a new property
Sample Problem 3:- Using the Object.fromEntries() method
Problem statement:- Swapnil wants to create an object with the product ID as the key and the product details as the value from an array of objects that provide the product information. What will he do?
Solution:-
Solution Code:-
const products = [
{ id: 1, name: 'Product 1', price: 10 },
{ id: 2, name: 'Product 2', price: 20 },
{ id: 3, name: 'Product 3', price: 30 },
{ id: 4, name: 'Product 4', price: 40 },
{ id: 5, name: 'Product 5', price: 50 }
];
const productsObj = Object.fromEntries(products.map(p => [p.id, { name: p.name, price: p.price }]));
console.log(productsObj);
Output:-
{
'1': { name: 'Product 1', price: 10 },
'2': { name: 'Product 2', price: 20 },
'3': { name: 'Product 3', price: 30 },
'4': { name: 'Product 4', price: 40 },
'5': { name: 'Product 5', price: 50 }
}
Explanation:-
- We have an array of products that contains objects representing the product details.
- Each object in the array is transformed using the map() function into an array with two elements: the product ID and an object with the product name and price.
- We pass the resulting array of arrays to the Object.fromEntries() method, which creates a new object with the product IDs as keys and the product details as values.
Conclusion
Finally, there are several techniques on how to change array to object in javascript, including using a for loop, Array.prototype.reduce(), and Object.fromEntries(). Each method has advantages and disadvantages, and the ideal method to utilize is determined by the unique use case and personal choice.
Consider readability, performance, and ease of use while selecting an approach. If you need to perform further operations, the Object.fromEntries() method is an excellent choice if you want a concise and clean solution.
The for loop method is a simple and traditional solution to solve this problem, and it can be a smart choice if you require additional control over the conversion process.