How to convert a list of object to an object in Javascript

When we use JS to request data from a (relational) database, the most common way we receive the data, is as a list of objects.

Often these data has the first values repeated because for example, are the days worked by a person or the purchases made by a customer.

In my work often i need to convert this list of object in hierarchical object, i.e. a multilevel json, or in other words a tree. After some specific conversion I decided to invest some time to build a generic function where the deep of the tree depends by the number of the keys passed to the function.

Since I don’t think I’m the only one with such a need, I decided to share this code with you all.

The function generateDictFromListOfObj require 3 params:
- the data: list of objects to convert
- the levelsKeys: list of keys to use to buld the tree
the valuesKeys: list of keys the are the value keys to use in the leave nodes

Visit Now