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
401 views
in Technique[技术] by (71.8m points)

javascript - Merge two arrays matching an id

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

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

1 Answer

0 votes
by (71.8m points)

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

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

2.1m questions

2.1m answers

60 comments

57.0k users

...