Computer >> Computer tutorials >  >> Programming >> Javascript

How to invert an object in JavaScript?


Inverting an object is one of the difficult tasks until underscore.js, a javascript framework, came into light. It has many functions in which _.invert() is one of them. This method actually inverts the key/value pairs. For suppose let an object has a key/value like name/Kiran. Then after inverting the object using _.invert() method the key/value pair changes into Kiran/name. Lets' discuss it, in a nutshell, using examples.

syntax

_.invert(object);

This method takes an object as an argument and inverts it. It changes the key/value pair into value/key pair.

Example -1

In the following example 'name', 'salary' and 'age' of a person were inverted into their value/key pairs.

<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
   var res = JSON.stringify(_.invert({name: 'Raj', age: 38, "salary": 120000}));
   document.write((res));
</script>
</body>
</html>

Output

{"38":"age","120000":"salary","Raj":"name"}

Example-2

In the following example 'name', 'Organization' and 'age' of a person were inverted into their value/key pairs.

<html>
<body>
<script  
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script type="text/javascript">
      var res = JSON.stringify(_.invert({"name": 'ElonMusk',age: 47, "Organization":'Spacex' }));
      document.write((res));
   </script>
</body>
</html>

Output

{"47":"age","ElonMusk":"name","Spacex":"Organization"}