Open In App

Underscore.js _.invert() Function

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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: "GeeksforGeeks",
            Address: "Noida",
            Contact: "+91 9876543210",
            Email: "[email protected]"
        }
        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:


Next Article

Similar Reads