a function to take the elements of an object & swap the keys with values & return it in typescript

Here's the TypeScript code that will take an input object, swap its keys with values and return the resulting object:

index.ts
function swapKeysWithValues(obj: { [key: string]: any }): { [key: string]: any } {
  const swappedObj: { [key: string]: any } = {}; // create an empty object to store swapped key-value pairs

  Object.keys(obj).forEach(key => {
    const value = obj[key];
    swappedObj[value] = key; // swap key-value and add to the swappedObj
  });

  return swappedObj;
}
359 chars
11 lines

With this function, you can pass any object as input and get the corresponding object with key-value pairs swapped. The function uses Object.keys() to get the keys of the input object and then iterates over them using forEach(). For each key-value pair, the function swaps the key with the value and adds it to the swappedObj. Finally, the function returns the swappedObj object.

Here's an example of how to use this function:

index.ts
const obj = { name: 'John', age: 30, city: 'New York' };
const swappedObj = swapKeysWithValues(obj); // { 'John': 'name', '30': 'age', 'New York': 'city' }
156 chars
3 lines

In this example, the obj object has its keys swapped with its values using the swapKeysWithValues function. The resulting swappedObj object has key-value pairs swapped and returned by the function.

gistlibby LogSnag