Convert an Array into an Object in JavaScript

Jul 31, 2020

In JavaScript, arrays are technically objects.

const arr = ['hello', 'world'];

arr instanceof Object; // true

For example, you can use Object.keys() and Object.entries() to get all the array's keys.

Object.keys(arr); // ['0', '1']
Object.entries(arr); // [ [ '0', 'hello' ], [ '1', 'world' ] ]

However, sometimes it is convenient to convert an array into a POJO. The easiest way to do that is using Object.assign():

const obj = Object.assign({}, arr);

obj instanceof Object; // true
Array.isArray(obj); // false

obj; // { '0': 'hello', '1': 'world' }

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!