javascript - Merge many-to-one list of objects -


i have 2 database tables currently, representing many-to-one relationship. activities, have id (integer, autoincrement, primary key) , name (varchar(255), not null); , activityslugs, have id (same above), slugname (not null varchar), , activity_id (foreign key activities.id).

currently i'm supposed list of activities , of slugs (as 1 list), looks this:

[     {id: 1, name: "long name", slugs: ["nick", "names"]},     {id: 2, name: "foobar", slugs: ["foo", "bar"]} ] 

the naive solution (and 1 can think of) "select *" on each table, , merge them, data looks this:

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} ] 

so can iterate on both , add them:

activities.foreach(function(activity) {     slugs = [];     activityslugs.foreach(function(slug) {         if (slug.activity_id == activity.id) {             slugs.push(slug.name);         }     });     activity.slugs = slugs; ); 

this feels clumsy, slow, , unrefined. won't scale @ all. unfortunately, can't seem find better way them merge many-to-one array this.

you can construct id2activity map access activity id:

var id2activity = {}; activities.foreach(function(activity) {     activity.slugs = [];     id2activity[activity.id] = activity; );  activityslugs.foreach(function(slug) {     id2activity[slug.activity_id].slugs.push(slug.name); }); 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -