How to Convert an Array's Values to Object Keys in JavaScript
A common data transformation task is to convert an array of strings into an object where each string from the array becomes a key. This is a powerful technique for creating lookup tables or "sets" for fast and efficient existence checks.
This guide will teach you the most effective methods for this conversion. We'll start with the modern and recommended approach using Object.fromEntries(), cover the functional reduce() method, and compare them to the classic manual loop, helping you choose the best tool for your needs.
The Modern Method (Recommended): Object.fromEntries() with map()
The Object.fromEntries() method is the most declarative and readable way to accomplish this. It is specifically designed to create an object from an iterable of [key, value] pairs.
The logic:
- Start with your array of keys (e.g.,
['name', 'age']). - Use the
map()method to transform this array into an array of[key, value]pairs (e.g.,[['name', ''], ['age', '']]). - Pass this new array directly to
Object.fromEntries().
For example, how to convert this array ['name', 'age', 'country'] into {name: '', age: '', country: '' }?
const keys = ['name', 'age', 'country'];
Solution: this clean, one-line solution is the best practice.
const keys = ['name', 'age', 'country'];
const defaultValue = '';
const obj = Object.fromEntries(
keys.map(key => [key, defaultValue])
);
console.log(obj); // Output: { name: '', age: '', country: '' }
This method clearly communicates the intent and is highly efficient.
The Functional Method: Array.prototype.reduce()
Another powerful, functional approach is to use the Array.prototype.reduce() method. This method iterates over an array to "reduce" it to a single final value—in our case, the new object.
const keys = ['name', 'age', 'country'];
const obj = keys.reduce((accumulator, currentKey) => {
accumulator[currentKey] = '';
return accumulator;
}, {}); // The `{}` is the initial value for our accumulator.
console.log(obj); // Output: { name: '', age: '', country: '' }
How it works: The reduce method starts with an empty object ({}). On each iteration, it adds a new key to this object (the accumulator) and then returns the modified object for the next iteration.
The Manual Looping Method: forEach or for...of
The classic imperative approach is to create an empty object and manually populate it within a loop. This is more verbose but can be easier to understand for beginners.
const keys = ['name', 'age', 'country'];
const obj = {};
keys.forEach(key => {
obj[key] = '';
});
console.log(obj); // Output: { name: '', age: '', country: '' }
While this works perfectly, the functional methods like Object.fromEntries() and reduce() are generally preferred in modern JavaScript for their conciseness and declarative style.
Practical Example: Creating a Lookup Table for Fast Checks
A primary use case for this conversion is to create a "set" or lookup object for highly efficient existence checks. Checking for a key in an object ('key' in obj) is much faster (O(1)) than searching an array (array.includes('key')), which is O(n).
Problem: you have a list of valid user roles, and you need to check if a given user's role is valid, potentially many times.
const validRoles = ['admin', 'editor', 'viewer', 'contributor'];
const user = { name: 'Alice', role: 'editor' };
Solution:
const validRoles = ['admin', 'editor', 'viewer', 'contributor'];
// Create the lookup object
const roleLookup = Object.fromEntries(
validRoles.map(role => [role, true])
);
/* roleLookup is now:
{
admin: true,
editor: true,
viewer: true,
contributor: true
}
*/
// Perform a fast, efficient check
const user = { name: 'Alice', role: 'editor' };
if (roleLookup[user.role]) {
console.log(`${user.name} has a valid role.`);
} else {
console.log(`${user.name} has an invalid role.`);
}
// Output: Alice has a valid role.
Conclusion
There are several effective ways to convert an array of values into object keys in JavaScript.
- The
Object.fromEntries(array.map(...))method is the recommended best practice. It is the most modern, declarative, and readable approach. - The
reduce()method is a powerful functional alternative that is also highly effective. - Manual looping with
forEachorfor...ofis a perfectly valid but more verbose, imperative approach.
For creating clean, modern, and maintainable code, Object.fromEntries() is the superior choice.