Sling Academy
Home/TypeScript/TypeScript: How to Convert Object to Array and Vice-Versa

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

Last updated: January 08, 2024

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.

Next Article: TypeScript error: Not assignable to type ‘never’

Previous Article: TypeScript: Converting an Array of Strings to an Array of Objects

Series: TypeScript: Intermediate & Advanced Tutorials

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)