Functional way of joining two js object arrays based on common id

a 夏天 提交于 2019-12-06 05:22:10

问题


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!


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/23591371/functional-way-of-joining-two-js-object-arrays-based-on-common-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!