DEV Community

Convert a 2D array to an object in JavaScript

Victor Peter on September 22, 2023

Here is a brief tutorial about how to convert JavaScript 2D array to a array of objects. Here is a array we want to convert: let arrToObj = [ ...
Collapse
 
jonrandy profile image
Jon Randy 🎖️

Your code is turning a 2D array into an array of objects, not a single object.

This will turn it into an object:

const result = Object.fromEntries(arrToObj)
Enter fullscreen mode Exit fullscreen mode

Or, if you want more explicit but likely slower code:

const result = arrToObj.reduce(
  (obj, [k, v]) => ((obj[k] = v), obj),
  {}
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
victuk profile image
Victor Peter

Owww, my bad, sorry. I saved the post as a draft the first time I wroe it, so when I came back to publish it, I just looked at the code and not the texts before the code, sorry. I wanted to turn it into an array, but your solution is really great...