Explain Codes LogoExplain Codes Logo

How to convert an array into an object?

javascript
reduce
array-to-object
javascript-features
Nikita BarsukovbyNikita BarsukovยทAug 30, 2024
โšกTLDR

From zero to hero - convert an array into an object swiftly using Object.fromEntries:

// Press the magic button ๐ŸŽฉ, courtesy of Object.fromEntries const arr = ['a', 'b', 'c']; const obj = Object.fromEntries(arr.map((v, i) => [i, v])); console.log(obj); // Outputs: {0: 'a', 1: 'b', 2: 'c'}; // Alice, Bob, and Charlie are now residing in a cozy object ๐Ÿ 

Using reduce for array to object transformation

Captain reduce() is here for efficient and clean array to object conversion:

const array = ['A', 'B', 'C']; // Reduce, reuse, recycle โ™ป๏ธ - saving the world one object at a time const objectWithReduce = array.reduce((obj, item, index) => { obj[index] = item; return obj; }, {}); console.log(objectWithReduce); // Outputs: {0: 'A', 1: 'B', 2: 'C'}

Dealing with missing elements in arrays

Beware of the holes! "Undefined" elements can be a thorn in your conversion process, but we can handle them just fine:

const sparseArray = ['A', , 'C']; // Nothing gets past me! ๐Ÿ‘€ - avoiding undefined intruders const objectFromSparseArray = sparseArray.reduce((obj, item, index) => { if (item !== undefined) { obj[index] = item; } return obj; }, {}); console.log(objectFromSparseArray); // Outputs: {0: 'A', 2: 'C'}

Modern JavaScript to the rescue - Using ES6 spread

Your ES6 survival kit has the spread operator {...array} that makes it a breeze to convert arrays to objects:

const es6Array = ['X', 'Y', 'Z']; // Ladies and gentlemen, start your engines ๐ŸŽ๐Ÿ’จ - ES6 spread const objectWithSpread = {...es6Array}; console.log(objectWithSpread); // Outputs: {0: 'X', 1: 'Y', 2: 'Z'}

Conquest from the end - reduceRight

Do you fancy starting from the other end? reduceRight() would be the weapon of your choice:

const reversedArray = ['end', 'middle', 'start']; // Back to the Future: reduceRight Edition ๐Ÿ”™ const objectWithReduceRight = reversedArray.reduceRight((obj, item, index) => { obj[index] = item; return obj; }, {}); console.log(objectWithReduceRight); // Outputs: {0: 'start', 1: 'middle', 2: 'end'}

Polyfills - Supporting older browsers

To ensure your code runs smoothly even on Jurassic-era browsers ๐Ÿฆ–, enter the world of polyfills:

Polyfill for Array.prototype.reduce:

if (!Array.prototype.reduce) { Array.prototype.reduce = function(callback /*, initialValue*/) { // Polyfill for reduce: Because every browser deserves to reduce() ๐ŸŒ }; }

Polyfill for Object.keys:

if (!Object.keys) { Object.keys = function(obj) { // Polyfill for Object.keys: Opening locked doors ๐Ÿšช }; }

Taking reduce to the next level

See how reduce can do wonders by switching keys and values in an array of objects:

const people = [{name: 'Alice'}, {name: 'Bob'}, {name: 'Charlie'}]; // Swapping places, keys and values are dancing the cha-cha-cha ๐Ÿ’ƒ๐Ÿ•บ const swapKeyValue = people.reduce((obj, item, index) => { const key = Object.keys(item)[0]; obj[item[key]] = index; return obj; }, {}); console.log(swapKeyValue); // Outputs: {Alice: 0, Bob: 1, Charlie: 2}

Pulling keys in objects away from array indices

Numeric keys in objects are like wild horses - free from the orderliness of array indices. They are strings and march to the beat of their own drum, sorting entries in the order they were added to the object.