Languages

JavaScript - create object from 2d array

0 points
Asked by:
Welsh
902

How can I convert 2D array to an object?

Let's say I have the following array of key/value pairs:

and the result I want to get is:

1 answer
0 points
Answered by:
Admin Dirask Community
4380

1. Using reduce() method (ES6+)

You can use reduce() method to initialize the accumulator with an empty object which will be returned as a result. Then, on every iteration, assign the current value as the key of the accumulator and set its value. At the end it returns the accumulator object.

2. Alternative solution

As an alternative solution for older versions of JavaScript, you can simply loop through the array, for example using forEach(), to assign the key/value pairs to an empty object and return it at the end.

 

References

  1. Array.prototype.reduce() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join