DEV Community

Cover image for Convert an Array to an Object in JavaScript
Rohit Kumawat
Rohit Kumawat

Posted on • Edited on

Convert an Array to an Object in JavaScript

Scenario-1: If you want to convert an array [1,2,3] to an object with keys being the index of the array, then you can use Object.assign and spread operator.

example:

let myArr = [1,2,3];

// use destructuring
{...myArr} // {0: 1, 1: 2, 2: 3}
Enter fullscreen mode Exit fullscreen mode

Scenario-2: Suppose you receive a list of data in response from API and you want to cluster them with respect to date.

We can use the Array reduce method to convert that array to an object.

let myArray = [
  {data: [1,2,3], date: '1/3/2012'},
  {data: [1,2,3,10,11], date: '3/6/2012'},
  {data: [1,2,3,4,5], date: '2/5/2012'}
]

myArray.reduce((lastUpdatedValue, currentValue) => {
  lastUpdatedValue[currentValue.date] = currentValue.data;
  return lastUpdatedValue;
}, {});

output: 
{
  1/3/2012: [1, 2, 3]
  2/5/2012: [1, 2, 3, 4, 5]
  3/6/2012: [1, 2, 3, 10, 11]
}
Enter fullscreen mode Exit fullscreen mode

Reduce method takes initial value which will be lastUpdatedValue on first iteration and on each iteration we can just add key & value pair to that object.

On each iteration starting from empty object, date as key and data as value will be added to the object.

Thank you for reading!

Top comments (0)