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

Categories

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

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

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...