基于公共ID连接两个js对象数组的功能方式 [英] Functional way of joining two js object arrays based on common id
问题描述
我试图用最优雅的(功能性)方式实现类似于SQL表连接的
,最好是使用underscore.js,
,所以请不要使用for循环。
我需要合并来自两个不同数组的对象,并使用一个公共标识符进行匹配。
例如,给定:
var basic = [{
id:'1',
name:'someName',
},
{...}]
var ext = [{
id:'1',
job:'someJob',
},
{...}]
结果应该是:
var combined = [{
id:'1',
name:'someName',
job:'someJob',
},
{...}]
谢谢!
var combined = _解决方案
Map,findWhere and extend should do the trick: .map(basic,function(base){
return _.extend(base,_.findWhere(ext,{id:base.id}));
});
编辑:
如果性能出现问题,请创建扩展值的哈希值:
var extHash = _.reduce(ext,function (备忘录,扩展,密钥){
备忘录[extended.id] = extended;
返回备忘录;
},{});
并如此使用:
<$ p $ (base,function(base){
return _.extend(base,extHash [base.id]);
});
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!
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]);
});
这篇关于基于公共ID连接两个js对象数组的功能方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!