Open In App

Lodash _.invert() Method

Last Updated : 03 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.invert() method is used to return the copy of an object where the object key is converted into value and object value is converted into the key. If the object contains duplicate values, subsequent values overwrite property assignments.

Syntax:

_.invert(object);

Parameters:

  • object: This parameter holds the object to invert.

Return Value:

This method returns the new inverted object.

Example 1: In this example, we are inverting the given object with the help of the lodash _.invert() method.

Javascript




// Requiring the lodash library 
const _ = require("lodash");
 
// Given object
let obj = { 'a': 1, 'b': 2, 'c': 3 };
 
// Use of _.invert method
console.log(_.invert(obj));


Output:

{ '1': 'a', '2': 'b', '3': 'c'}

Example 2: In this example, we are inverting the given object with the help of the lodash _.invert() method. as b and c both have the same value that’s why it will only add the last key which is c.

Javascript




// Requiring the lodash library 
const _ = require("lodash");
 
// Given object
let obj = { 'a': 1, 'b': 2, 'c': 2 };
 
// Use of _.invert method
console.log(_.invert(obj));


Output:

{ '1': 'a', '2': 'c' }

Example 3: In this example, we are inverting the given object with the help of the lodash _.invert() method.

Javascript




/// Requiring the lodash library 
const _ = require("lodash");
 
// Given object
let obj = {
    Name: "GeeksforGeeks",
    password: "gfg@1234",
    username: "your_geeks"
}
 
// Use of _.invert method
console.log(_.invert(obj));


Output:

{GeeksforGeeks: "Name", 
gfg@1234: "password",
your_geeks: "username"}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads