title: Converting large number of database results into array of objects in javascript
body: <p>I am pulling a database query that has the following info:</p>
  
  <p><code>id, name, roleId, roleTitle</code></p>
  
  <p>In the query, I am pulling for users and their roles. Each user can have 0 to N number of roles. I want to in the end have an object like this:</p>
  
  <pre><code>{
      id
      name
      roles: [{
         id
         title
      }]
  }
  </code></pre>
  
  <p>What would the most efficient way of doing this be? Currently I am doing something like this:</p>
  
  <pre><code>const data = [];
  arr.forEach((u) =&gt; {
     const index = data.findIndex(x =&gt; x.id === u.id);
      if (index &gt;= 0) {
        data[index].roles.push({ id: u.roleId, title: u.roleTitle });
      } else {
        data.push({
          id: u.id,
          name: u.name,
          roles: u.roleId ? [{
            id: u.roleId,
            title: u.roleTitle,
          }] : [],
        });
      }
  }
  </code></pre>
  
  <p>This solution works correctly but wasn't sure if this was the fastest way to get this done if we scale the user numbers to 10k with an average role per user of 3 or 50k and 5 roles per user</p>