【问题标题】:How to compare 2 different objects with different fields and create a new object with a new field that tells common elements如何比较 2 个具有不同字段的不同对象并创建一个具有告诉共同元素的新字段的新对象
【发布时间】:2021-12-08 06:36:32
【问题描述】:

我有

obj1= [{keyID: 'c71cc89335565241f59ac9bb9da162a3ddf4a6b483bdc06dd82b9275898ba5ee', name: 'user1@mail.com'},
 {keyID: '34051d2554ab20b0d24c2c39946d96da7e07508e7a8546bc2df299601dcbff05', name: 'user2@mail.com'}]

obj2=[{id: 19, email: 'user4@mail.com', other_field: false},
  {id: 221, email: 'user3@mail.com', other_field: false},
{id: 13, email: 'user2@mail.com', other_field: false)},
 {id: 2, email: 'user1@mail.com', other_field: true]

如您所见,obj1 keyIDobj2 ID 不同,这很好。我想将它们分组的东西是名称(obj1)和电子邮件(obj2) 具有相同电子邮件的字段应该创建一个具有相同结构的新对象 obj2 和一个新字段“isPresent

result=[{id: 19, email: 'user4@mail.com', other_field: false,isPresent=false},
  {id: 221, email: 'user3@mail.com', other_field: false,isPresent=false},
{id: 13, email: 'user2@mail.com', other_field: false,isPresent=true)},
 {id: 2, email: 'user1@mail.com', other_field: true,isPresent=true]

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript arrays typescript


    【解决方案1】:

    您可以通过obj2 map 并通过some 检查obj1 中是否存在同名元素。

    我也在地图里面spreadobj而不是直接分配isPresent以避免副作用。

    const obj1 = [{ keyID: 'c71cc89335565241f59ac9bb9da162a3ddf4a6b483bdc06dd82b9275898ba5ee', name: 'user1@mail.com' }, { keyID: '34051d2554ab20b0d24c2c39946d96da7e07508e7a8546bc2df299601dcbff05', name: 'user2@mail.com' }];
    const obj2 = [{ id: 19, email: 'user4@mail.com', other_field: false }, { id: 221, email: 'user3@mail.com', other_field: false }, { id: 13, email: 'user2@mail.com', other_field: false }, { id: 2, email: 'user1@mail.com', other_field: true }];
    const result = obj2.map((obj) => ({
      ...obj,
      isPresent: obj1.some(({ name }) => name === obj.email),
    }));
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 2012-04-03
      • 2019-06-14
      • 2019-07-17
      • 1970-01-01
      相关资源
      最近更新 更多