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 arrays like

var members = [{docId: "1234", userId: 222}, {docId: "1235", userId: 333}];
var memberInfo = [{id: 222, name: "test1"}, {id: 333, name: "test2"}];

I need to merge this to a single array programatically matching the user ids

The final array should be like

var finalArray = [{docId: "1234", userId: 222, name: "test1"}, {docId: "1235", userId: 333, name: "test2"}]

Is there a cleaner way to do this, I have underscore library in my app, but I couldn't find a clean method to achieve this

See Question&Answers more detail:os

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

1 Answer

A solution using underscore:

var finalArray = _.map(members, function(member){
    return _.extend(member, _.omit(_.findWhere(memberInfo, {id: member.userId}), 'id'));
});
  1. _.map across the members
  2. find the matching member info using _.findWhere
  3. _.omit the id key from the matching member info
  4. _.extend the member with the member info

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