合并两个匹配id的数组

编程入门 行业动态 更新时间:2024-10-26 03:24:07
本文介绍了合并两个匹配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')); });

  • _。map
  • 使用 _。findWhere
  • _。延伸 会员信息
  • _.map across the members
  • find the matching member info using _.findWhere
  • _.omit the id key from the matching member info
  • _.extend the member with the member info
  • 更多推荐

    合并两个匹配id的数组

    本文发布于:2023-10-20 09:00:12,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1510522.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数组   两个   id

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!