Convert array to identity object
JavaScript, Array · Apr 16, 2023

Converts an array of values into an object with the same values as keys and values.
- Use
Array.prototype.map()
to map each value to an array of key-value pairs. - Use
Object.fromEntries()
to convert the array of key-value pairs into an object.
const toIdentityObject = arr => Object.fromEntries(arr.map(v => [v, v]));
toIdentityObject(['a', 'b']); // { a: 'a', b: 'b' }
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.