How to convert an array to object in javascript?
Here, we will learn how to convert an array into an object in javascript. we will use Object.assign() method and spread operators to convert it to an object.
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:
Related Posts
Find the average of n numbers using JavaScript
Tutorial to write a JavaScript function to find the average of n numbers of items in an Array using JavaScript.
Best way - Split an array into half in Javascript
To divide an single array into half i.e into two different arrays without modifying the original array we can use Array.slice() method in JavaScript.
Merge Two Arrays and Remove Duplicates - JavaScript
Tutorial on how to merge two or more array and remove duplicates in JavaScript.
How to multiply all numbers in an array using JavaScript
Quick tutorial on how to multiply all the elements in an array using iterative i.e loop and reduce method in JavaScript.
