Search code examples
javascripttypescriptjavascript-objectsngrxkeyvaluepair

typescript: How to get objects with the same property values but different keys from 2 different sets of Objects


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

objetSet1:
  {id: 12, name: 'Foo Bar', email: '[email protected]'},
  {id: 23, name: 'Bar Foo', email: '[email protected]'},
  {id: 61, name: 'Barbell', email: '[email protected]'},
  {id: 45, name: 'Joe Ocean', email: '[email protected]'}

objectSet2:
  {ObjectId:15, name: 'someone', email: '[email protected]'},
  {ObjectId: 23, name: 'sometwo', email: '[email protected]'},
  {ObjectId: 72, name: 'seven ', email: '[email protected]'},
  {ObjectId: 23, name: 'five ', email: '[email protected]'}

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

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

instead of 23 static value, the value from objectSet1 corresponding

the result should contain Item with ids present on the first object set

expected output:

objectSet2:
      {ObjectId: 23, name: 'sometwo', email: '[email protected]'},
      {ObjectId: 23, name: 'five ', email: '[email protected]'}

Solution

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

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

    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.