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"] ];
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);
The result will be:
[ { name: 'Victor' }, { language: 'JavaScript' }, { country: 'Nigeria' }, { mood: 'Happy Mode' } ]
Top comments (2)
Your code is turning a 2D array into an array of objects, not a single object.
This will turn it into an object:
Or, if you want more explicit but likely slower code:
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...