Home > Software design >  How to merge two Api array results in to one in angular
How to merge two Api array results in to one in angular

Time:07-19

My first api array results are like below:

{name: 'ABC', state: 'AR', licenseNumber: '100108512'}
{name: 'DEF', state: 'KY', licenseNumber: '100108518'}

My second api array results are like below:

{rollnum: '20' name: 'KGF', state: 'NE', licenseNumber: '1628740'}

I would like to see the output like below

{name: 'ABC', state: 'AR', licenseNumber: '100108512'}
{name: 'DEF', state: 'KY', licenseNumber: '100108518'}
{name: 'KGF', state: 'NE', licenseNumber: '1628740' }

I have tried concat and spread syntax but it did not work may be because 1st api has 3 properties and 2nd api has 4 properties( but 3 properties are common in both).

Any suggestion to achieve above output in Angular 9 or above?

CodePudding user response:

Just map and concat:

// example
let first = [{ name: 'ABC', state: 'AR', licenseNumber: '100108512' }, { name: 'DEF', state: 'KY', licenseNumber: '100108518' }];

// example
let second = [{ rollnum: '20', name: 'KGF', state: 'NE', licenseNumber: '1628740' }];

// use this common function to map the results in each set to the desired shared outcome
// if you have different logic or properties for mapping (e.g. map FirstName to Name) then make different mapping functions or change mapping logic in same function.
let mappingFunc = (item) => { return { name: item.name, state: item.state, licenseNumber: item.licenseNumber }; };

// final result contains desired result
const finalResult = first.map(mappingFunc).concat(second.map(mappingFunc))

console.log(finalResult);

  • Related