JavaScript Create an Object From Two Arrays (original) (raw)

Last Updated : 13 Jan, 2025

**Here are the different methods to create an object from two arrays in JavaScript

**1. Using for-each loop

The arr.forEach() method calls the provided function once for each element of the array.

JavaScript `

//Driver Code Starts const a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 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: 'Ajay', age: 25, city: 'New Delhi' }

**In this example

**2. Using reduce() method

The reduce() method provides a functional programming approach to build the object.

JavaScript `

//Driver Code Starts const a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 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: 'Ajay', age: 25, city: 'New Delhi' }

**In this example

**3. Using Object.assign method

The Object.assign() method is used to copy the values and properties from one or more source objects to a target object.

JavaScript `

//Driver Code Starts const a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 25, 'New Delhi'];

//Driver Code Ends

const res = Object.assign({}, ...a1.map((key, index) => ({ [key]: a2[index] })));

//Driver Code Starts

console.log(res); //Driver Code Ends

`

Output

{ name: 'Ajay', age: 25, city: 'New Delhi' }

**In this example

4. **Using object.fromEntries() Method

The **Object.fromEntries() **method in JavaScript is a standard built-in object which is used to transform a list of key-value pairs into an object.

JavaScript `

const a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 25, 'New Delhi'];

const res = Object.fromEntries(a1.map((key, index) => [key, a2[index]]));

console.log(res);

`

Output

{ '1': 'ram', '2': 'shyam', '3': 'sita', '4': 'gita' }

**In this example

Which Approach Should You Choose?

Similar Reads