There are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches –
Using reduce()
const array = [['name', 'Josh'], ['age', 25], ['city', 'New York']];
const obj = array.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
console.log(obj); // Output: { name: 'Josh', age: 25, city: 'New York' }
In the above example, we have used the reduce method that iterates over each pair, destructuring them into key
and value
. It then assigns each value to its corresponding key in the accumulator object.
Using Object.fromEntries()
const array = [['name', 'Josh'], ['age', 25], ['city', 'New York']];
const obj = Object.fromEntries(array);
console.log(obj); // Output: { name: 'Alice', age: 25, city: 'New York' }
The Object.fromEntries() method in JavaScript is a standard built-in method used to transform a list of key-value pairs into an object.
Similar Reads
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order