Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two arrays of objects using underscore

I have two array of objects:

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

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}]
like image 884
Tomislav Avatar asked May 20 '26 07:05

Tomislav


1 Answers

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

If you want to fiddle (See what I did there) with it: http://jsfiddle.net/b90pyxjq/3/

like image 105
Aurélien Thieriot Avatar answered May 21 '26 19:05

Aurélien Thieriot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!