打字稿:如何从2套不同的对象集中获取具有相同属性值但键不同的对象 [英] typescript: How to get objects with the same property values but different keys from 2 different sets of Objects

查看:99
本文介绍了打字稿:如何从2套不同的对象集中获取具有相同属性值但键不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从状态数据表格中获取Json的集合

I have to sets of Json got from the form the state data

objetSet1:
  {id: 12, name: 'Foo Bar', email: 'foo@bar.com'},
  {id: 23, name: 'Bar Foo', email: 'bar@foo.com'},
  {id: 61, name: 'Barbell', email: 'barbell@mail.com'},
  {id: 45, name: 'Joe Ocean', email: 'joe@ocean.com'}

objectSet2:
  {ObjectId:15, name: 'someone', email: 'someone@mail.com'},
  {ObjectId: 23, name: 'sometwo', email: 'sometwo@mail.com'},
  {ObjectId: 72, name: 'seven ', email: 'seven@mail.com'},
  {ObjectId: 23, name: 'five ', email: 'five@mail.com'}

我实际上是在寻找一种使该表达式具有动态性的方法

I was actually looking for a way to get this expression to be dynamic

objectSet2 = objectSet2.filter(object => object.ObjectId === '23')

objectSet1中的值代替了23个静态值

instead of 23 static value, the value from objectSet1 corresponding

结果应包含第一个对象集上存在ID的项目

预期输出:

objectSet2:
      {ObjectId: 23, name: 'sometwo', email: 'sometwo@mail.com'},
      {ObjectId: 23, name: 'five ', email: 'five@mail.com'}

推荐答案

Yoy接近了,只需要添加一个新的过滤器,像这样:

Yoy were close, just needed to add a new filter like this:

objetSet1 = [{id: 12, name: 'Foo Bar', email: 'foo@bar.com'},
  {id: 23, name: 'Bar Foo', email: 'bar@foo.com'},
  {id: 61, name: 'Barbell', email: 'barbell@mail.com'},
  {id: 45, name: 'Joe Ocean', email: 'joe@ocean.com'}];
  
  objectSet2 = [{ObjectId:15, name: 'someone', email: 'someone@mail.com'},
  {ObjectId: 23, name: 'sometwo', email: 'sometwo@mail.com'},
  {ObjectId: 72, name: 'seven ', email: 'seven@mail.com'},
  {ObjectId: 23, name: 'five ', email: 'five@mail.com'}];
  
 var result = objectSet2.filter((obj2)=>objetSet1.filter((obj1)=>obj1.id==obj2.ObjectId).length>0)
 
 console.log(result);

请注意obj1.id==obj2.ObjectId的比较.当内部过滤器上的正匹配计数大于零时,它返回true.这就是外部过滤器的答案.

Please note obj1.id==obj2.ObjectId comparison. It's returning true when the count of positive matches on the inner filter is greater than zero. Then this is the answer for the outer filter.

这篇关于打字稿:如何从2套不同的对象集中获取具有相同属性值但键不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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