Convert Array to Object in JavaScript
- 1 minute read
The following function will take an array and spit out an object, with a property for each array item and its value:
const toObject = (arr) => {
return Object.assign({}, arr);
};
Here’s how you can use it:
const arr = [`red`, `blue`, `yellow`];
const obj = toObject(arr);
Once the above code has executed, obj
will equal {"0": "red", "1": "blue", "2": "yellow"}
.
Notice how a property is created for each array item, with the key set to the item’s location in the array and the value set to the item itself.
Here is a one-liner toObject
implementation with the same behavior:
const toObject = (arr) => Object.assign({}, arr);
By the way, you can also just use this shorthand method instead of Object.assign:
const arr = [`red`, `blue`, `yellow`];
const obj = {...arr};
Conclusion
I hope this little snippet helped you out!
I’ve found converting arrays to objects especially useful when preparing API responses.