Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

javascript - 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}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...