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

Underscore is a library of functions for dealing with complex data structures in JavaScript. One of its most useful functions is the invert function, which swaps the keys and values of an object.

The basic syntax for _.invert(obj) is:

index.tsx
_.invert(obj)
14 chars
2 lines

Here's an example of how to use _.invert(obj):

index.tsx
const _ = require("underscore");

const obj = {
    'item1': 'value1',
    'item2': 'value2',
    'item3': 'value3'
};

const invertedObj = _.invert(obj);

console.log(invertedObj);
182 chars
12 lines

This will output:

index.tsx
{
  value1: 'item1',
  value2: 'item2',
  value3: 'item3'
}
60 chars
6 lines

Here, _.invert(obj) takes the obj object and swaps the keys and values, returning the invertedObj object.

gistlibby LogSnag