网站搜索

javascript - 如何比较两个具有不同字段的不同对象,并创建一个带有新字段的新对象,该字段显示共同的元素


我有

obj1= [{keyID: 'c71cc89335565241f59ac9bb9da162a3ddf4a6b483bdc06dd82b9275898ba5ee', name: '[email '},
 {keyID: '34051d2554ab20b0d24c2c39946d96da7e07508e7a8546bc2df299601dcbff05', name: '[email '}]

和

obj2=[{id: 19, email: '[email ', other_field: false},
  {id: 221, email: '[email ', other_field: false},
{id: 13, email: '[email ', other_field: false)},
 {id: 2, email: '[email ', other_field: true]

如你所见,我有 obj1 keyID 与 obj2 ID 不同,这是可以的。我想要按名称(obj1)和邮箱(obj2)对它们进行分组,具有相同邮箱的字段应该创建一个新的对象,结构与 obj2 相同,并新增一个字段 "isPresent"

result=[{id: 19, email: '[email ', other_field: false,isPresent=false},
  {id: 221, email: '[email ', other_field: false,isPresent=false},
{id: 13, email: '[email ', other_field: false,isPresent=true)},
 {id: 2, email: '[email ', other_field: true,isPresent=true]

我如何才能实现那一点?

答案#1

你可以对 obj2 使用 map,并通过 some 检查 obj1 中是否存在具有相同名称的元素。

我也在 map 内部展开了 obj,而不是直接赋值 isPresent,以避免副作用。

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