how to use the invert function from the underscore library in typescript

To use the invert() function from the Underscore library in TypeScript, you first need to install the library via npm:

index.ts
npm install underscore
23 chars
2 lines

Then, you can import it in your TypeScript file like this:

index.ts
import * as _ from 'underscore';
33 chars
2 lines

Assuming you have an object with key-value pairs and want to swap the keys and values, you can use the invert() function like this:

index.ts
const originalObject = { name: 'John', age: 30, occupation: 'Developer' };
const invertedObject = _.invert(originalObject);
console.log(invertedObject); // { 'John': 'name', '30': 'age', 'Developer': 'occupation' }
215 chars
4 lines

This will create a new object with the values of the original object as keys, and the keys of the original object as values. The invert() function works with both string and number values.

gistlibby LogSnag