How to convert a list of object to an object in Javascript
<p>When we use JS to request data from a (relational) database, the most common way we receive the data, is as a <strong>list </strong>of <strong>objects</strong>.</p>
<p>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.</p>
<p>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 <em>tree</em>. After some specific conversion I decided to invest some time to build a <em>generic </em>function where the <em>deep</em> of the <em>tree</em> depends by the number of the keys passed to the function.</p>
<p>Since I don’t think I’m the only one with such a need, I decided to share this code with you all.</p>
<p>The function <strong>generateDictFromListOfObj </strong>require 3 params:<br />
- the <strong>data: </strong>list of objects to convert<br />
- the <strong>levelsKeys</strong>: list of keys to use to buld the <em>tree<br />
- </em>the <strong>valuesKeys</strong>: list of keys the are the <em>value</em> keys to use in the <em>leave</em> nodes</p>
<p><a href="https://stefanogiostra-it.medium.com/how-to-convert-a-list-of-object-to-an-object-in-javascript-5da20991c167">Visit Now</a></p>