take the elements of an object & swap the keys with values in typescript

To take the elements of an object and swap the keys with values in TypeScript, one effective approach is to iterate over the object's key-value pairs and construct a new object in the process. The following function is an implementation of this approach:

index.ts
function swapKeysAndValues(obj: { [key: string]: any }) {
  const entries = Object.entries(obj);
  const result: { [key: string]: any } = {};
  
  entries.forEach(([key, value]) => result[value] = key);
  
  return result;
}
225 chars
9 lines

In this function, we first obtain an array of key-value pairs using the Object.entries() method. We then initialize an empty object that will hold the transformed data.

We then use the forEach() method to iterate through the entries array, destructure each key-value pair, and construct the new key-value pair in the result object by assigning the value as the key and the key as the value.

Finally, we return the transformed object.

Here's an example usage of the function:

index.ts
const myObj = { a: 1, b: 2, c: 3 };
const swappedObj = swapKeysAndValues(myObj);
console.log(swappedObj); // { '1': 'a', '2': 'b', '3': 'c' }
142 chars
4 lines

gistlibby LogSnag