how to use the invert function from lodash in javascript

To use the invert function in lodash, you first need to install the lodash library using npm (Node Package Manager) by running the following command in your terminal:

index.tsx
npm install lodash
19 chars
2 lines

Once you have installed the lodash library, you can use the invert function to create a new object composed of keys from the original object and their corresponding values as keys:

index.tsx
const _ = require('lodash');

const originalObj = {
  'key1': 'value1',
  'key2': 'value2',
  'key3': 'value3'
};

const invertedObj = _.invert(originalObj);

console.log(invertedObj);
// Output: { 'value1': 'key1', 'value2': 'key2', 'value3': 'key3' }
253 chars
13 lines

In the code above, we import the lodash library using the require function and create an object called originalObj with three key-value pairs. We then use the invert function from lodash to create a new object called invertedObj, which has the values of originalObj as keys and their respective keys as values. Finally, we log the invertedObj to the console, which outputs a new object with the inverted key-value pairs.

Note that the invert function does not modify the original object, but instead returns a new object with inverted key-value pairs.

gistlibby LogSnag