2
let fruit = {
  id: 1,
  isGood: false
}

lets say I have a function call that accepts an id of a fruit object and returns an observable that resolves into a boolean indicating whether the value isGood is true or false.

I want to map through an array of fruit objects and call the function described above then use the value returned to set isGood on an object and set an id from the fruit on the same object that is returned.

In my mind, I should be able to do something like this:

forkJoin(
  fruitArray.map(fruit => { 
     return of({ 
       "data": isFruitGood(fruit.id)),
       "id": fruid.id
      })
    })  
   ).subscribe(result => console.log(result))

The problem here is that an array of objects is returned, but the observable set to data in the object is not resolving.

1 Answers1

2

Your problem is that your forkJoin is unwrapping your of observable, but not the inner observable returned in your "data" property.

You need to pass forkJoin an array of the observables that get the isFruitGood value for you, then after those come back, build your objects:

forkJoin(fruitArray.map(
  fruit => isFruitGood(fruit.id)
)).pipe(
  map(isGoodArray => isGoodArray.map(
    (isGood, i) => ({
      data: isGood,
      id: fruitArray[i].id
    })
  )
)).subscribe(result => console.log(result))

here's a sample StackBlitz

BizzyBob
  • 12,309
  • 4
  • 27
  • 51
  • so you have to use the indexes of arrays? There's no way to attach the id in someway instead of using indexes? – Trevor Lane Mar 07 '21 at 17:21
  • One thing about forkJoin, is that the returned array will be in the same order as the source, so the indexes will always match up. You can also pass a dictionary type object (key is ID, value is the isFruitGood(id)) to forkJoin, then when the data comes back from forkJoin, you could look it up by `id` rather than index. I added a second example to the StackBlitz. Not sure it's better, but just shows how it could look. – BizzyBob Mar 07 '21 at 19:34