JavaScript: Create an Object from Arrays of Keys and Values

Updated: March 14, 2023 By: Khue Post a comment

This succinct, straightforward article walks you through 5 different approaches to creating an object from 2 arrays of keys and values in JavaScript. The main point here is to make sure the keys and values in the 2 arrays are aligned in terms of their positions, meaning that the first key in the keys array should correspond to the first value in the values array, and so on.

Using Object.fromEntries()

The Object.fromEntries() method takes a list of key-value pairs and returns a new object with those properties. We can make use of it to construct an object based on 2 given arrays.

Examples:

let keys = ['name', 'age', 'gender'];
let values = ['Sling Academy', 325, 'unknown'];

let obj = Object.fromEntries(
    keys.map((key, index) => [key, values[index]]));

console.log(obj);

Output:

{ name: 'Sling Academy', age: 325, gender: 'unknown' }

Using a traditional for loop

The for loop is a powerful tool for many problems, and in the context of this article, it is also true.

Example:

// the array of keys
let keys = ['a', 'b', 'c'];

// the array of values
let values = [1, 2, 3];

// Create an empty object
let obj = {};

for (let i = 0; i < keys.length; i++) {
  obj[keys[i]] = values[i];
}

console.log(obj);

Output:

{ a: 1, b: 2, c: 3 }

Using reduce()

Example:

let keys = ['a', 'b', 'c'];
let values = [1, 2, 3];
let obj = keys.reduce((acc, key, index) => {
  acc[key] = values[index];
  return acc;
}, {});

console.log(obj);

Output:

{ a: 1, b: 2, c: 3 }

See also: Ways to Compare 2 Objects in JavaScript

Using Object.assign()

This method is quite similar to the first method; only the difference is that we use the Object.assign() method.

Example:

// the array of keys
let keys = ['a', 'b', 'c'];

// the array of values
let values = [1, 2, 3];

let obj = Object.assign(
  {},
  ...keys.map((key, index) => ({ [key]: values[index] }))
);

console.log(obj);

Output:

{ a: 1, b: 2, c: 3 }

Using forEach()

Example:

// the array of keys
let keys = ['a', 'b', 'c'];

// the array of values
let values = [1, 2, 3];

let obj = {};

// Iterate over the keys array and assign properties to the object
keys.forEach((key, index) => {
  obj[key] = values[index];
});

console.log(obj);

Output:

{ a: 1, b: 2, c: 3 }

See also: The Modern JavaScript Objects Cheat Sheet

Afterword

We’ve explored more than one technique to build an object from 2 arrays of keys and values. Which one will you use in your project? Please leave your opinion in the comment section. Happy coding & have a nice day!