A functional way to combine two arrays of js objects based on a common identifier

I am trying to achieve something similar to joining an SQL table in the most elegant (functional) way, preferably using underscore.js, so no for loops, please.

I need to combine objects from two different arrays, consistent with a common identifier.

For example, given:

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

The result should be:

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

Thanks!

+4
source share
2 answers

The map, findWhere and extension should do the trick:

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

Edit

If performance is a problem, create a hash of extended values:

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

and use like this:

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

Fiddle

+3
source

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

inherits are known to be the following:

 function inherits(base, extension) { for ( var property in base ) { extension[property] = base[property]; } return extension ; } 
0
source

Source: https://habr.com/ru/post/1240639/


All Articles