Question

I am trying to acheive something similar to SQL table join, in the most elegant (functional) way, preferably with underscore.js, so no for loops please.

I need to merge objects from two different arrays, matched upon a common identifier.

For example, given:

var basic = [{
              id: '1',
              name: 'someName',
             }, 
             {...} ]

var ext= [{
              id: '1',
              job: 'someJob',
             }, 
             {...} ]

Result should be:

var combined = [{
                 id: '1',
                 name: 'someName',
                 job: 'someJob',
                }, 
                {...} ]

Thanks!

Was it helpful?

Solution

Map, findWhere and extend should do the trick:

var combined = _.map(basic, function(base){
    return _.extend(base, _.findWhere(ext, { id: base.id} ));
});

Edit:

If performance is an issue create a hash of the extended values:

var extHash = _.reduce(ext, function(memo, extended, key){
    memo[extended.id] = extended;
    return memo;
}, {});

and use like so:

var combined = _.map(basic, function(base){
    return _.extend(base, extHash[base.id]);
});

Fiddle

OTHER TIPS

NO LOOP : http://jsfiddle.net/abdennour/h3hQt/2/

   basic=basic.sort(function(a,b){return a.id-b.id});
    ext=ext.sort(function(a,b){return a.id-b.id});
    var combined=basic.map(function(e,i){return inherits(e,ext[i]) });

Known that ,inherits are as following:

function inherits(base, extension)
{
   for ( var property in base )
   { 
         extension[property] = base[property];
   }
    return extension ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top