title: Merge many-to-one list of objects
body: <p>I have two database tables currently, representing a many-to-one relationship. Activities, which have an ID (integer, autoincrement, primary key) and a name (varchar(255), not null); and ActivitySlugs, which have an ID (same as above), a slugname (not null varchar), and an activity_id (foreign key to Activities.id).</p>
  
  <p>Currently I'm supposed to get a list of all activities and all of their slugs (as one list), so that it looks something like this:</p>
  
  <pre><code>[
      {id: 1, name: "long name", slugs: ["nick", "names"]},
      {id: 2, name: "foobar", slugs: ["foo", "bar"]}
  ]
  </code></pre>
  
  <p>The naive solution (and about the only one I can think of) is to do a "SELECT *" on each table, and then merge them, but then I get data that looks like this:</p>
  
  <pre><code>activities = [
      {id: 1, name: "long name"},
      {id: 2, name: "foobar"}
  ]
  slugs = [
      {id: 1, slugname: "nick", activity_id: 1},
      {id: 2, slugname: "names", activity_id: 1},
      {id: 3, slugname: "foo", activity_id: 2},
      {id: 4, slugname: "bar", activity_id: 2}
  ]
  </code></pre>
  
  <p>So then I can iterate over both and add them:</p>
  
  <pre><code>activities.forEach(function(activity) {
      slugs = [];
      activitySlugs.forEach(function(slug) {
          if (slug.activity_id == activity.id) {
              slugs.push(slug.name);
          }
      });
      activity.slugs = slugs;
  );
  </code></pre>
  
  <p>This feels clumsy, slow, and unrefined. It certainly won't scale at all. Unfortunately, I can't seem to find a better way to get them to merge as a many-to-one with an array like this. </p>