Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two array of objects of different sizes, based on a property in Javascript?

I have two arrays of objects that are different in length but share similar information.

qrySearchLocID = [{
    LocalLabID: '123f',
    SystemID: 5000152,
    AppLabID: 3
  },
  {
    LocalLabID: '12BC',
    SystemID: 5000384,
    AppLabID: 3
  },
];

and

qrySearch = [{
    sName: 'SomePlace1',
    lBusinessID: 37343,
    SystemID: 5000152
  },
  {
    sName: 'SomePlace2',
    lBusinessID: 39780,
    SystemID: 5000156
  },
  {
    sName: 'SomePlace3',
    lBusinessID: 50772,
    SystemID: 5000519
  },
  {
    sName: 'SomePlace4',
    lBusinessID: 31079,
    SystemID: 5000384
  },
]

I want to combine these two arrays based on the SystemID, copy all the information from qrySearch and add the LocalLabID from qrySearchLocID and nothing else. For example I want the result array to be

[{
    sName: 'SomePlace1',
    lBusinessID: 37343,
    SystemID: 5000152,
    LocalLabID: '123f'
  },
  {
    sName: 'SomePlace2',
    lBusinessID: 39780,
    SystemID: 5000156
  },
  {
    sName: 'SomePlace3',
    lBusinessID: 50772,
    SystemID: 5000519
  },
  {
    sName: 'SomePlace4',
    lBusinessID: 31079,
    SystemID: 5000384,
    LocalLabID: '12BC'
  },
]

Thanks in advance.

like image 512
CRod Avatar asked Dec 05 '25 16:12

CRod


1 Answers

You can use map and find functions.

var qrySearchLocID = [{
    LocalLabID: '123f',
    SystemID: 5000152,
    AppLabID: 3
  },
  {
    LocalLabID: '12BC',
    SystemID: 5000384,
    AppLabID: 3
  },
];

var qrySearch = [{
    sName: 'SomePlace1',
    lBusinessID: 37343,
    SystemID: 5000152
  },
  {
    sName: 'SomePlace2',
    lBusinessID: 39780,
    SystemID: 5000156
  },
  {
    sName: 'SomePlace3',
    lBusinessID: 50772,
    SystemID: 5000519
  },
  {
    sName: 'SomePlace4',
    lBusinessID: 31079,
    SystemID: 5000384
  },
];

var result = qrySearch.map((e, _) => 
          (_ = qrySearchLocID.find((q) => q.SystemID === e.SystemID)) ? 
          { ...e, ...{ LocalLabID: _.LocalLabID } } : e);

console.log(result);

Resources

  • Array.prototype.map()
  • Array.prototype.find()
like image 146
Ele Avatar answered Dec 08 '25 05:12

Ele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!