DEV Community

Victor Peter
Victor Peter

Posted on

Convert a 2D array to an object in JavaScript

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 = [
  ["name", "Victor"],
  ["language", "JavaScript"],
  ["country", "Nigeria"],
  ["mood", "Happy Mode"]
];
Enter fullscreen mode Exit fullscreen mode

Here is the code to convert the 2d array to an array of objects.

const result = arrToObj.map(arr => {
    let obj = {};
    obj[arr[0]] = arr[1];
    return obj
});

console.log(result);
Enter fullscreen mode Exit fullscreen mode

The result will be:

[
  { name: 'Victor' },
  { language: 'JavaScript' },
  { country: 'Nigeria' },
  { mood: 'Happy Mode' }
]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

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...