Получение первого значения при фильтрации наблюдаемого массива

#javascript #rxjs

#javascript #rxjs

Вопрос:

Допустим, у меня есть наблюдаемый массив с такой структурой, как:

 let arr = Observable.of([{a: null}, {a: [1,2,3,4]}, {a: [1,2,3]}, {a: null}])
  

И я хочу извлечь первый объект, которого a нет null . Как я могу вернуть {a: [1,2,3,4]} ?

Ответ №1:

Вы можете попробовать что-то вроде этого

 let arr = Observable.of([{a: null}, {a: [1,2,3,4]}, {a: [1,2,3]}, {a: null}])

arr
.pipe(
  // with this map you transform the array emitted by the source into the first item where a is not null
  map(a => a.find(item => !!item.a))  // find is the array method
)
.subscribe(
  // the data emitted here can be null if all items in the original array have an a property null
  data => console.log("I am the first item with a not null, if any", data)
)