Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 334
Prats Avatar asked Aug 31 '25 18:08

Prats


2 Answers

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
like image 197
Gruff Bunny Avatar answered Sep 02 '25 06:09

Gruff Bunny


You can achieve using foreach function and creating the third array and displaying it.

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

angular.forEach($scope.members, function(member) {
    angular.forEach($scope.memberInfo, function(memberInfo) {
      if(member.userId ==memberInfo.id) {
          var test = {
            docId : member.docId,
            userId: member.userId,
            name: memberInfo.name
          }
          $scope.finalArray.push(test);
      }
  });
});

Here is the working plunker:

http://embed.plnkr.co/QRB5v2cI6SZOdZgdqDVR/preview

Hope it helps!

like image 24
Alhuck Avatar answered Sep 02 '25 08:09

Alhuck