Functional way of joining two js object arrays based on common id
functional-programming, javascript, underscore.js
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
Problem
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!