How to use the invert function from underscore
Find comprehensive JavaScript underscore.invert code examples handpicked from public code repositorys.
underscore.invert is a function that returns an object with the keys and values of a given object reversed.
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922
'>': '>', '"': '"', "'": ''' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
How does underscore.invert work?
underscore.invert
works by taking a single input, which is an object that you want to invert.
The function returns a new object where the keys of the original input object become the values of the new object, and the values of the input object become the keys of the new object.
If multiple keys have the same value, the last key encountered will be the value in the inverted object.
By using underscore.invert
, you can quickly and easily swap the keys and values of an object, which can be useful when working with data where you need to look up values based on keys or vice versa.
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
const _ = require("underscore"); // Define an object with keys and values const originalObject = { key1: "value1", key2: "value2", key3: "value3", }; // Invert the keys and values of the object const invertedObject = _.invert(originalObject); // Log the original and inverted objects console.log(originalObject); // { key1: 'value1', key2: 'value2', key3: 'value3' } console.log(invertedObject); // { value1: 'key1', value2: 'key2', value3: 'key3' }
In this example, we first define an object originalObject with keys and values. We then pass originalObject to _.invert to create a new object where the keys and values are reversed. We log both the original and inverted objects to the console. The resulting output demonstrates how underscore.invert can be used to invert the keys and values of an object.
underscore.keys is the most popular function in underscore (11266 examples)