[Fixed] Combine two array objects with exactly the same structure

Issue

I am implementing a service that extracts a list of blacklist terms from a json file.

@Injectable()
export class BlacklistService {
  private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist';
  private readonly blacklistEnglishTerms: any;
  private readonly blacklistFrenchTerms: any;

  constructor(
    public httpClient: HttpClient
  ) {
    this.blacklistEnglishTerms = this.httpClient.get(`${this.BLACKLIST_FOLDER}/en.json`);
    this.blacklistFrenchTerms = this.httpClient.get(`${this.BLACKLIST_FOLDER}/fr.json`);
  }

  public getAllBlackListTerms(): Observable<any> {
    return combineLatest([
      this.blacklistEnglishTerms,
      this.blacklistFrenchTerms
    ]);
  }
}

For reference, each json file looks like this:

{
  "blacklist": [
    "...",
    "...",
    "..."
  ]
}

I retrieve all the items in my component as follows:

this.blacklistService.getAllBlackListTerms().pipe(takeUntil(this.ngUnsubscribe)).subscribe(blacklistTerms => {
  console.log(blacklistTerms);
});

blacklistTerms returns as an array of 2 array objects. How do I combine these two objects into one object (both have the same structure).

enter image description here

Solution

Given, you have known results, i.e. You know that the results of the bolth the Observbales would have only one key: blackList you can modify your service like:

public getAllBlackListTerms(): Observable<any> {
    return zip(
        this.blacklistEnglishTerms,
        this.blacklistFrenchTerms
    ).pipe(map([first, second]) => {
        return { blackList: [...first.blackList, ...second.blackList]};
    });
}

I have also, replaced combineLatest() with zip(), because you probably want the results only when both has emitted values.

Leave a Reply

(*) Required, Your email will not be published