In JavaScript, you can create an object from two arrays by using one array for keys and the other for their corresponding values.
- Each element of the first array becomes an object key.
- The element at the same index in the second array becomes its value.
- Methods such as forEach(), reduce(), Object.assign(), and Object.fromEntries() can be used.
Approach 1: Using forEach()
The forEach() method iterates through the keys array and uses the index to access the corresponding value from the second array.
Example: In this example, we use forEach() to create an object from two arrays.
//Driver Code Starts
const a1 = ['name', 'age', 'city'];
const a2 = ['Alen', 25, 'New Delhi'];
//Driver Code Ends
const res = {};
a1.forEach((key, index) => {
res[key] = a2[index];
//Driver Code Starts
});
console.log(res);
//Driver Code Ends
Output
{ name: 'Alen', age: 25, city: 'New Delhi' }
Approach 2: Using reduce()
The reduce() method can build the object by using an empty object as the accumulator and adding each key-value pair to it.
Example: In this example, we use reduce() to create an object from two arrays.
//Driver Code Starts
const a1 = ['name', 'age', 'city'];
const a2 = ['Alen', 25, 'New Delhi'];
//Driver Code Ends
const res = a1.reduce((obj, key, index) => {
obj[key] = a2[index];
return obj;
}, {});
//Driver Code Starts
console.log(res);
//Driver Code Ends
Output
{ name: 'Alen', age: 25, city: 'New Delhi' }
Approach 3: Using Object.assign()
The Object.assign() method can merge multiple objects into a single object. We can use map() to create individual key-value objects and then merge them.
Example: In this example, we use Object.assign() to combine the key-value pairs.
//Driver Code Starts
const a1 = ['name', 'age', 'city'];
const a2 = ['Alen', 25, 'New Delhi'];
//Driver Code Ends
const res = Object.assign(
{},
//Driver Code Starts
...a1.map((key, index) => ({
[key]: a2[index]
}))
);
console.log(res);
//Driver Code Ends
Output
{ name: 'Alen', age: 25, city: 'New Delhi' }
Approach 4: Using Object.fromEntries()
The Object.fromEntries() method converts an iterable of key-value pairs into an object. It provides a concise way to combine two arrays.
Example: In this example, we use map() to create key-value pairs and Object.fromEntries() to create the object.
const a1 = ['name', 'age', 'city'];
const a2 = ['Alen', 25, 'New Delhi'];
const res = Object.fromEntries(
a1.map((key, index) => [key, a2[index]])
);
console.log(res);
Output
{ name: 'Alen', age: 25, city: 'New Delhi' }