TypeScript: How to Convert Object to Array and Vice-Versa

Updated: January 8, 2024 By: Guest Contributor Post a comment

Overview

In the versatile world of TypeScript, transforming the shape of our data is like alchemy, finding gold in rows as arrays or nuggets as objects. This tutorial will take you from the simple spells to transmute objects into arrays and back again, with each incantation proving more potent than the last.

Converting an Object to an Array

Objects in TypeScript, much like a river, are a constant flow of key-value pairs, where each key is a unique identifier of its corresponding value. However, unlike the mighty Mississippi, objects cannot be traversed with the simplicity of a steamboat paddlewheel. In order to navigate through them, we must gather their contents into a vessel more akin to our rowboat—an array.

An object can be reshaped into an array using various methods such as Object.keys, Object.values, and Object.entries. Here’s a piece of code as straightforward as honest work:

const obj = { key1: 'value1', key2: 'value2' };
const keys = Object.keys(obj); // ['key1', 'key2']
const values = Object.values(obj); // ['value1', 'value2']
const entries = Object.entries(obj); // [['key1', 'value1'], ['key2', 'value2']]

Converting an Array to an Object

An array, much like a handful of corn kernels, can be popped into an object – a sturdy bag that has a place for every unique kernel. We achieve this using methods such as reduce:

const arr = [['key1', 'value1'], ['key2', 'value2']];
const obj = arr.reduce((accumulator, [key, value]) => ({ ...accumulator, [key]: value }), {});
console.log(obj); // { key1: 'value1', key2: 'value2' }

Advanced Transformations

Moving to the alchemic arts, we can transform our objects and arrays with more sophistication using generics, mapping them like uncharted territories down to every typed detail for TypeScript’s eyes:

function convertObjectToArray<T>(obj: T): [keyof T, T[keyof T]][] {
     return Object.entries(obj) as [keyof T, T[keyof T]][];
}

Another dazzling trick is to cast a net that gathers only the properties you wish to keep, a pied piper’s tune for only those that match the melody:

type SelectiveConversion<T, K extends keyof T> = {
     [P in K]: T[P];
 };
 function selectiveConvertToArray<T, K extends keyof T>(obj: T, keys: K[]): SelectiveConversion<T, K>[] {
     return keys.map(k => ({ [k]: obj[k] }));
}

Conclusion

A good day’s work it’s been, converting objects to arrays, and arrays to objects—akin to turning lead into gold. The spells and prayers outlined herein will serve you mightily as you stride confidently through the TypeScript wilderness, artfully transmuting data structures as the task at hand requires.