1

Component 1

this.service.myArray['artists'] = data;

Component 2

Component two receives each of the artist IDs through an @Input property. I then perform a query to fetch all of the albums. Each album document has an 'artist_id' property.

  @Input() artist_id: string;

  ----

  ngOnInit(): void {
    this.albums$ = this.service
      .getAlbums$(var1, var2, etc)
      .pipe(
        filter((data) => !!data),
        take(1),
        map((data) => {
          // logic here?
          return data;
        })
      );
  }

How can I loop through my returned albums and inject them into the myArray array based on matching artist_id? For example, any returned albums that have an artist_id that is equal to the document ID of the items in the artists array (myArray[artists]) are pushed into the correct position:

myArray:
artists:
 - 0 { 
    title: 'title', 'id': '1234',
    albums: 
    - 0 { 'album 1', artist_id: '1234' }
    - 1 { 'album 2', artist_id: '1234' }
    },
 - 1 { 
    title: 'title 2', 'id': '4321',
    albums: 
    - 0 { 'album 3', artist_id: '4321' }
    - 1 { 'album 4', artist_id: '4321' }
    },

UPDATE

I have it working. Not entirely sure if it's elegant.

ngOnInit(): void {
    this.albums $ = service
      .getAlbums$(properties)
      .pipe(
        filter((data) => !!data),
        take(1),
        tap((data) => {
          this.updateArray(data);
          return data;
        })
      );
  }

  updateArray(data) {
    data.forEach((album) => {
      this.service.myArray["artists"].find((artist) => {
        if (artist.id === item.artist_id) {
          this.albums.push(album);
          artist["albums"] = this.albums;
        }
      });
    });
  }
Wytrzymały Wiktor
  • 11,492
  • 5
  • 29
  • 37
Que
  • 957
  • 2
  • 14
  • 35
  • Does this [thread](https://stackoverflow.com/questions/50019787/compare-an-id-to-an-array-in-cloud-firestore-with-angular) answers your question? – Farid Shumbar Oct 05 '21 at 10:57
  • Hi Farid. No it doesn't. Firestore's involvement in this question is simply to fetch data. My main question is how to push the retrieved data into an existing array into a specific position based on matching IDs – Que Oct 05 '21 at 11:10

1 Answers1

0

Posting @Que's solution for visibility:

ngOnInit(): void {
    this.albums $ = service
      .getAlbums$(properties)
      .pipe(
        filter((data) => !!data),
        take(1),
        tap((data) => {
          this.updateArray(data);
          return data;
        })
      );
  }

  updateArray(data) {
    data.forEach((album) => {
      this.service.myArray["artists"].find((artist) => {
        if (artist.id === item.artist_id) {
          this.albums.push(album);
          artist["albums"] = this.albums;
        }
      });
    });
  }
Farid Shumbar
  • 1,360
  • 3
  • 10