Underscore.js _.invert() Function

Underscore.js _.invert() function 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. It means the [key, value] of the object is reversed.

Syntax:

_.invert( object );

Parameters:

  • object: It contains the object element that holds the elements of key and value pair.

Return Value:

It returns the [key, value] of an object in reverse [value, key] order.

Example 1: The below code will explain the implementation of the _.invert() function in underscore.js.

html




<!DOCTYPE html>
<html>
 
<head>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
    </script>
</head>
 
<body>
    <script type="text/javascript">
        const obj = {
            Company: "w3wiki",
            Address: "Noida",
            Contact: "+91 9876543210",
            Email: "abc@gfg.com"
        }
        console.log(_.invert(obj));
    </script>
</body>
 
</html>


Output:

Example 2: The below code example is another implementation of the _.invert() function.

html




<!DOCTYPE html>
<html>
 
<head>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
    </script>
</head>
 
<body>
    <script type="text/javascript">
 
        const inv = _.invert({
            num1: 10,
            num2: 20,
            num3: 30,
            num4: 40
        });
 
        console.log(inv);
    </script>
</body>
 
</html>


Output:



Contact Us