I have been trying to get these two array objects merged into one. I tried multiple solutions posted on Stackoverflow, but somehow my problem is little different than standard Merges.
Elements from each array from first object(arrObj1 ) need to merge with second object (arrObj2) based on the key (id).
Since second object have same key value(id:1 - two times, and id:2 - two times) multiple times, I am having challenge to figure it out.
arrObj1 = [
{ id: 1,
name: 'Jack',
date: '09/05/2018',
web_ref_id: '311102010201210'},
{ id: 2,
name: 'Smith',
date: '09/12/2018',
web_ref_id: '1111201311111203'} ]
arrObj2 = [
{ id: 1,
changes_id: 1,
city: 'Chicago',
Zip: '12345',
street_name: 'Rockhill Dr',
web_ref_id: '311102010201210'},
{ id: 1,
changes_id: 1,
city: 'Chicago',
Zip: '12345',
street_name: 'Cambridge Dr',
web_ref_id: '311102010201210'},
{ id: 2,
changes_id: 2,
city: 'New York',
Zip: '43435',
street_name: 'Smithson Dr',
web_ref_id: '1111201311111203' },
{ id: 2,
db_changes_id: 2,
changes_id: 2,
city: 'New York',
Zip: '43435',
street_name: 'Lombard Blvd',
web_ref_id: '1111201311111203' } ]
Expected Result:
arrObj3 = [
{ id: 1,
name: 'Jack',
date: '09/05/2018',
changes_id: 1,
city: 'Chicago',
Zip: '12345',
street_name: 'Rockhill Dr',
web_ref_id: '311102010201210'},
{ id: 1,
name: 'Jack',
date: '09/05/2018',
changes_id: 1,
city: 'Chicago',
Zip: '12345',
street_name: 'Cambridge Dr',
web_ref_id: '311102010201210'},
{ id: 2,
name: 'Smith',
date: '09/12/2018'
changes_id: 2,
city: 'New York',
Zip: '43435',
street_name: 'Smithson Dr',
web_ref_id: '1111201311111203' },
{ id: 2,
name: 'Smith',
date: '09/12/2018'
db_changes_id: 2,
changes_id: 2,
city: 'New York',
Zip: '43435',
street_name: 'Lombard Blvd',
web_ref_id: '1111201311111203' } ]
Solution Tried:
var objArr3 = objArr1,
power = objArr2,
hash = new Map,
merged = power.map(a => {
var o = {};
Object.assign(o, a);
hash.set(a.id, o);
return o;
});
objArr3.forEach(a => hash.has(a.id) && Object.assign(hash.get(a.id), a));
Somehow this is skipping inserting into the first array of second object(objArr2).