EN
JavaScript - convert array to object with values as keys
3
points
In this article, we would like to show you how to convert array to object with array values as keys working with JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c'];
const object = array.reduce((object, item) => (object[item] = item, object), {});
console.log(JSON.stringify(object, null, 4));
or:
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c'];
const result = array.reduce((object, item) => ({...object, [item]: item}), {});
console.log(JSON.stringify(result, null, 4));
Warning: the solution based on spread operator is not recommended because of bad time performance.
Practical examples
In this examples, we create a reusable function that converts the array to object with the array values as keys using reduce() method.
1. Assigning property based example
// ONLINE-RUNNER:browser;
const toObject = (array) => {
return array.reduce((object, item) => (object[item] = item, object), {});
};
// Usage example:
const array = ['a', 'b', 'c'];
const object = toObject(array);
console.log(JSON.stringify(object, null, 4));
2. Spread operator based example
// ONLINE-RUNNER:browser;
const toObject = (array) => {
return array.reduce((object, item) => ({ ...object, [item]: item }), {});
};
// Usage example:
const array = ['a', 'b', 'c'];
const object = toObject(array);
console.log(JSON.stringify(object, null, 4));
Warning: the solution based on spread operator is not recommended because of bad time performance.