Languages
[Edit]
EN

JavaScript - convert array to object with values as keys

3 points
Created by:
a_horse
538

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.

 

See also

  1. JavaScript - convert array to object

References

  1. Spread syntax (...) - JavaScript | MDN

Alternative titles

  1. JavaScript - convert array to object with array values as keys
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join