How to Zip Two Arrays into an Object in JavaScript?

Estimated read time 1 min read

You can zip two arrays into an object in JavaScript using the Array.map() method and the Object.assign() method. Here’s an example

let keys = ['name', 'age', 'email'];
let values = ['John Doe', 30, 'johndoe@example.com'];

let obj = keys.reduce((acc, key, i) =>
  Object.assign(acc, { [key]: values[i] }), {});

console.log(obj); // { name: 'John Doe', age: 30, email: 'johndoe@example.com' }

In this example, two arrays keys and values are defined, and the Array.reduce() method is used to iterate over the keys array, creating a new object with properties and values from both arrays. For each iteration, the Object.assign() method is used to add a new property to the accumulator object acc, with the key from the keys array and the value from the values array. The result is an object that maps the keys from the first array to the values from the second array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply