合并两个匹配id的数组 [英] Merge two arrays matching an id

查看:430
本文介绍了合并两个匹配id的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,比如

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

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

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

最后一个数组应该像

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

推荐答案

使用下划线的解决方案:

A solution using underscore:

var finalArray = _.map(members, function(member){
    return _.extend(member, _.omit(_.findWhere(memberInfo, {id: member.userId}), 'id'));
});




  1. _。map

  2. 使用 _。findWhere


  3. _。延伸 会员信息

  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

这篇关于合并两个匹配id的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆