In this article we will learn how to convert an array to an object in JavaScript.
It is very common to convert an array to an object in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to convert an array to an object.
Imagine you have an array like this:
const myArray = [
['name', 'John'],
['age', 30],
['country', 'USA']
];
And we want to convert this array to an object, so the output will became like this:
{
name: 'John',
age: 30,
country: 'USA'
};
How to solve this problem?
Fortunately, there are many ways to solve this problem, and there are many built-in functions that can be used to solve this problem, such as:
- Using
Object.fromEntries()
. - Using
Object.assign
. - Using
reduce
method. - Using spread syntax
...
.
In this article, we will explain all solutions.
Convert array to object using Object.fromEntries()
As we said before, we can use Object.fromEntries()
method to convert our array to an object.
Let's see an example
// Array
const myArray = [
['name', 'John'],
['age', 30],
['country', 'USA']
];
// Convert to object
const toObj = Object.fromEntries(myArray);
// Result:
console.log(toObj);
Output
{ name: 'John', age: 30, country: 'USA' }
The Object.fromEntries() static method transforms a list of key-value pairs into an object. MDN
Convert array to object using Object.assign
We can use Object.assign
to solve this problem as well.
Let's see an example
// Array
const myArray = ['one', 'two', 'three'];
// Convert to an object
const toObj = Object.assign({}, myArray);
// Result:
console.log(toObj);
Output
{ '0': 'one', '1': 'two', '2': 'three' }
The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object. MDN
Convert array to object using reduce
We can use reduce
method to convert our array to object.
Example
// Array
const myArray = ['one', 'two', 'three'];
// Convert to an object
const toObj = myArray.reduce((accumulator, value, index) => {
return {...accumulator, [index]: value};
}, {});
// Result:
console.log(toObj);
Output
{ '0': 'one', '1': 'two', '2': 'three' }
The reduce()
method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. MDN
Convert array to object using spread operator
We can use spread operator to solve this problem as well.
Example
// Array
const myArray = ['one', 'two', 'three'];
// Convert to an object.
const toObj = { ...myArray };
// Result:
console.log(toObj);
Output
{ '0': 'one', '1': 'two', '2': 'three' }
Thank you for reading
Thank you for reading my blog. 🚀