使用下划线组合两个对象数组 [英] Combine two arrays of objects using underscore
本文介绍了使用下划线组合两个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个对象数组:
var a = [{id:456, name:'sojuz'},
{id:751, name:'sputnik'},
{id:56, name:'arianne'}]
var b = [{id:751, weight:5800},
{id:456, weight:2659},
{id:56, weight:6700}]
使用underscorejs如何将数组a扩展到新数组c从数组b添加权重属性,其中id属性相同:
Using underscorejs how to extend array a into new array c adding weight property from array b where the id property is the same:
var c = [{id:456, name:'sojuz', weight:2659},
{id:751, name:'sputnik', weight:5800},
{id:56, name:'arianne', weight:6700}]
推荐答案
这是用下划线做的一种方法:
This is one way of doing it with underscore:
var c = _.map(a, function(element) {
var treasure = _.findWhere(b, { id: element.id });
return _.extend(element, treasure);
});
如果你想用它来摆弄(看我在那里做了什么): http://jsfiddle.net/b90pyxjq/3/
If you want to fiddle (See what I did there) with it: http://jsfiddle.net/b90pyxjq/3/
这篇关于使用下划线组合两个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文