How to convert an array to object in javascript?

📋 Table Of Content
Here, in this article we will learn how to convert an array to an object using JavaScript. We will try to convert it in three different ways. 1. Using Object.assign() method 2. Using spread operators 3. Using the reduce() function.
What is Object.assign() method in JavaScript?
The Object.assign()
method is copies all enumerable and own properties from one or more sources to its target object. And then return the target object.
Syntax:
Object.assign(target, ...sources)
target
: it were you apply the source properties to. And it is returned after its modified.
source
: object which contain properties that you want to change.
Spread Operators : Spread syntax (...)
It takes iterable such as an array and expand it into individual elements.
reduce() method in javascript
It executes a reducer function for each value in an array and return a single value which is the accumulated result.
Now let see how to use the above functions and operators to convert an array to object.
Convert an array to object in JavaScript.
We will do the conversion from an array to an Object by the following solutions below.
Method 1: Using Object.assign() method
let Arr = ['a','b','c'];
const objArr = Object.assign({}, Arr);
console.log(objArr)
Output :
{ '0': 'a', '1': 'b', '2': 'c' }
Method 2 : Using Spread Operator
let Arr = ['a','b','c'];
const spread = { ...Arr }
console.log(spread)
Output:
{ '0': 'a', '1': 'b', '2': 'c' }
Method 3: With Custom key using reduce() method
It lets you convert JavaScript array to object of same keys/values.
let Arr = ['a','b','c'];
Arr.reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: 'a', b: 'b', c: 'c' }
That's it, this three are the easiest way to convert your array to an object using JavaScript.
Related Topics: