How to convert a JavaScript array of 2 element arrays into object key value pairs?

Sometimes, we want to convert a JavaScript array of 2 element arrays into object key value pairs.

In this article, we’ll look at how to convert a JavaScript array of 2 element arrays into object key value pairs.

How to convert a JavaScript array of 2 element arrays into object key value pairs?

To convert a JavaScript array of 2 element arrays into object key value pairs, we can use the Object.fromEntries method.

For instance, we write:

const array = [
  ['a', 1],
  ['b', 2],
  ['c', 3]
];
const object = Object.fromEntries(array);
console.log(object);

to call Object.fromEntries with an array of key-value pair arrays.

Therefore, object is {a: 1, b: 2, c: 3}.

Conclusion

To convert a JavaScript array of 2 element arrays into object key value pairs, we can use the Object.fromEntries method.