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:
xxxxxxxxxx
1
const array = ['a', 'b', 'c'];
2
const object = array.reduce((object, item) => (object[item] = item, object), {});
3
4
console.log(JSON.stringify(object, null, 4));
or:
xxxxxxxxxx
1
const array = ['a', 'b', 'c'];
2
const result = array.reduce((object, item) => ({object, [item]: item}), {});
3
4
console.log(JSON.stringify(result, null, 4));
Warning: the solution based on spread operator is not recommended because of bad time performance.
In this examples, we create a reusable function that converts the array
to object with the array
values as keys using reduce()
method.
xxxxxxxxxx
1
const toObject = (array) => {
2
return array.reduce((object, item) => (object[item] = item, object), {});
3
};
4
5
6
// Usage example:
7
8
const array = ['a', 'b', 'c'];
9
const object = toObject(array);
10
11
console.log(JSON.stringify(object, null, 4));
xxxxxxxxxx
1
const toObject = (array) => {
2
return array.reduce((object, item) => ({ object, [item]: item }), {});
3
};
4
5
6
// Usage example:
7
8
const array = ['a', 'b', 'c'];
9
const object = toObject(array);
10
11
console.log(JSON.stringify(object, null, 4));
Warning: the solution based on spread operator is not recommended because of bad time performance.