If I am ever in a situation in which I need to create an object with keys that are generated from the properties of objects in an array, or collection in general, I can use the lodash _.keyBy method to make quick work of that if lodash is there to work with in a project. The _.keyBy method works a lot like _.groupBy, and also the _.countBy methods only it will only create one key for each value in a source collection, rather than creating groups as needed for two or more elements that meet a condition, or give a count of elements that meet a condition.
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 the lodash keyby method though, at least when it comes to arrays alone anyway. Just using the array forEach or a loop of some kind to loop over the contents of the array, and use the value of each object to create key names to a new Object created with the object literal syntax for example.
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.