Skip to content

Instantly share code, notes, and snippets.

@pcakhilnadh
Last active June 17, 2021 19:08
Show Gist options
  • Save pcakhilnadh/68d6021fc758e529860571ee557f77b1 to your computer and use it in GitHub Desktop.
Save pcakhilnadh/68d6021fc758e529860571ee557f77b1 to your computer and use it in GitHub Desktop.
Merge two API Call response object into a third observable collection. Explanation :- I have two observables as shown below Observable <Array<Model1>> Observable <Array<Model2>> Model1 { id , first_name, last_name} Model 2{ id , class } What is the best way to convert it to observable 3 as shown below? where id in observable 1 and observable 2 …
/*
Summary
Merge two API Call response object into a third observable collection
Explanation
I have two observables as shown below
Observable <Array<Model1>>
Observable <Array<Model2>>
Model1 { id , first_name, last_name}
Model 2{ id , class }
What is the best way to convert it to observable 3 as shown below? where id in observable 1 and observable 2 are same.
Observable <Array<Model3>>
Model 3 { id, first_name, class }
*/
import { Component, OnInit } from '@angular/core';
import { forkJoin, Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
export class Model1 {
public id?: string;
public last?: string;
public first?: string;
}
export class Model2 {
public id?: string;
public className?: string;
}
export class Model3 {
public id?: string;
public className?: string;
public first?: string;
}
@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
public model1sObs: Observable<Model1[]> = of(
Array.from(['1', '2']).map(e => {
return {
id: e,
first: 'first' + e,
last: 'last' + e
};
})
);
public model2sObs: Observable<Model2[]> = of(
Array.from(['1', '2']).map(e => {
return {
id: e,
className: 'className' + e
};
})
);
constructor() {}
ngOnInit(): void {
forkJoin([this.model1sObs, this.model2sObs])
.pipe(map(([models1, models2]) => this.mergeByCompare(models1, models2)))
.subscribe(data => {
console.log(data);
});
}
public mergeByCompare(model1s: Model1[], model2s: Model2[]): Model3[] {
return model1s
.map(m1 => this.getMergedObj(m1, model2s))
.map(nM => this.convertToModel3(nM));
}
private getMergedObj(m1: Model1, model2s: Model2[]): any {
const nmodels: any[] = model2s
.filter(m2 => m2.id === m1.id)
.map(m2 => {
return { ...m1, ...m2 };
});
return nmodels && nmodels.length > 0 ? nmodels[0] : {};
}
private convertToModel3(nM: any): Model3 {
const model3: Model3 = new Model3();
model3.id = nM.id;
model3.className = nM.className;
model3.first = nM.first;
return model3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment