If I am every in a situation in which I need to create an object with keys that are generated from the properties of objects in an array I can use the lodash _.keyBy method to make quick work of that. The _.keyBy method works a lot like _.groupBy only it will only create one object for each key. In this post I will be going over some use case examples of _.keyBy, and some vanilla js alternatives for doing so as well.
Maybe it is a good idea to start out with a very simple example of the lodash _.keyby method. Maybe something where we are just working with a simple array of numbers, and I want an object where each key is the corresponding letter of the alphabet for that number.
So basically the returned value of of the method that is given to the lodash keyby method will be the object key name of the resulting key value pait object that will be returned by the keyby method.
For a basic example I just have an array of objects that each have a type and price property. I want to have a single object that has keys that are the type of an object in the array followed by a number. The _.keyBy method can be used in this case.
It is not to hard to make a vanilla js alternative to this.
So _.keyBy is one of the many methods in lo dash that can come in handle now and then when a situation comes about that calls for it’s use. If you have anything you might like to add, or have any questions or concerns about the content of this post please be sure to let me know in the comments, and thank you for reading.