How can I create an object from two arrays in JavaScript?
When working with JavaScript, a common task involves combining two arrays into an object. This often arises when you have one array containing keys and another containing corresponding values. Knowing the right method to do this efficiently can make your code cleaner and more effective. In this article, we will explore straightforward ways to create an object from two arrays, with clear examples to help you understand the process.
Imagine you have these two arrays:
Javascript
Your goal is to generate an object like:
Javascript
Method 1: Using a loop
One of the simplest ways to combine two arrays into an object is by using a for
loop. You iterate over the arrays, assigning each key-value pair to a new object.
Javascript
This code creates an empty object result
, then adds properties to it by matching elements from both arrays via their indices. This method is easy to understand and works well when both arrays are of the same length.
Method 2: Using Array.prototype.reduce()
The reduce()
method offers a more functional approach. You start with an empty object, then build it up as you iterate over the keys array. For each key, assign the corresponding value from the values array.
Javascript
This approach is concise and expressive. The reduce()
function takes an accumulator object, populates it with key-value pairs, and finally returns the complete object.
Method 3: Using Object.fromEntries()
with Array.prototype.map()
From ECMAScript 2019 onwards, JavaScript offers a very clean method called Object.fromEntries()
. It takes an array of key-value pairs and converts it into an object. To use it, combine the two arrays with map()
to create the pairs.
Javascript
This method is very elegant. It first creates an array of pairs, then transforms those pairs into an object with Object.fromEntries()
. It's especially handy when dealing with large datasets.
Important note
Ensure that both arrays are the same length; otherwise, some keys may not have corresponding values. If they differ in length, you can handle the mismatch explicitly, for example, by truncating the longer array or setting default values.
Creating an object from two arrays in JavaScript can be done in several ways:
- Using a simple
for
loop — straightforward and easy to understand. - Using
reduce()
— more functional and concise. - Using
Object.fromEntries()
combined withmap()
— modern and clean.
Choice of method depends on personal preference and your specific use case. The Object.fromEntries()
approach is recommended for its simplicity and readability when working with modern JavaScript environments.