Categories
JavaScript Answers

How to Merge Keys Array and Values Array into an Object in JavaScript?

Spread the love

To merge keys array and values array into an object in JavaScript, we can use the JavaScript array’s reduce method.

For instance, we write:

const keys = ['height', 'width'];
const values = ['1px', '2px'];
const merged = keys.reduce((obj, key, index) => ({
  ...obj,
  [key]: values[index]
}), {});
console.log(merged)

We have the keys and values array that has the property keys and their corresponding values.

Next, we call keys.reduce with a callback to get the key and put the key as the property name.

And the values[index] value is set as the value of [key].

We then return that object.

The 2nd argument of reduce is an empty object so obj is set to an empty object initially.

Therefore, merged is:

{height: "1px", width: "2px"}

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *