First Approach: In this example, we will demonstrate the conventional method of inverting key-value pairs. At first, a student object is created with properties “name”, “age”, “std” and “fees”. An inverse() function is defined which takes the student object as a parameter and loops through each key of the object. A new object retobj is defined which stores the inverted key value pairs.
Second Approach: In this example, we use the _.invert() method of “underscore.js” to invert the key value pairs of the object. The method takes the object as a parameter and returns a copy of the object with the keys as values and values as keys. The “student” object is passed to the _.invert() method. The method returns the inverted copy of the “student” object. The program imports the external “underscore.js” library to use inbuilt methods. The results are displayed on the webpage.
Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML course.