合并两个匹配id的数组

时间:2015-05-17 11:37:20

标签: javascript angularjs underscore.js

我有两个数组,比如

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

我需要将它合并到一个以编程方式匹配用户ID的单个数组

最终数组应该像

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

有没有更简洁的方法来做到这一点,我在我的应用程序中有下划线库,但我找不到一个干净的方法来实现这个

6 个答案:

答案 0 :(得分:8)

使用下划线的解决方案:

var finalArray = _.map(members, function(member){
    return _.extend(member, _.omit(_.findWhere(memberInfo, {id: member.userId}), 'id'));
});
  1. _.map各会员
  2. 使用_.findWhere
  3. 查找匹配的会员信息
  4. _.omit来自匹配成员信息的ID密钥
  5. _.extend会员信息
  6. 的会员

答案 1 :(得分:4)

您可以使用foreach function并创建第三个数组并显示它。

$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);
      }
  });
});

以下是工作人员:

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

希望它有所帮助!

答案 2 :(得分:1)

function computeMembers(members, memberInfo) {
  return members.map(function(member) {
    member.name = memberInfo[getMemberById(member.userId, memberInfo)].name
    return member
  })

  function getMemberById(id, elements) {
    var index = elements.filter(function(element) {
      return element.id === id
    })[0]
    return elements.indexOf(index)
  }
}

console.log(computeMembers(members, memberInfo))

答案 3 :(得分:0)

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

_.each(memberInfo, function (item) {
    finalArray.push(_.each(_.where(members, {
        userId: item.id
    }),

    function (element) {
        element.name = item.name
    }));
});

console.log(finalArray);

Fiddle example

答案 4 :(得分:0)

进行嵌套映射,并使用数组中的字段匹配的附加字段date更新顶层元素。

member.map(mem => {
    return memberInfo.map(info => {
        if (info.id === mem.userId) {
            mem.date = info.date;
            return mem;
        }
    }
}

答案 5 :(得分:-1)

在ES6上,你可以在vanilla javascript中使用.find和Object.assign(),不需要额外的库。

let finalArray = [];
memberInfo.forEach(member => {
finalArray.push( Object.assign( {}, member, 
         { docId: members.find(m => m.userId === member.id).docId } 
    ))
});