繁体   English   中英

从过滤可观察数组中获取第一个值

[英]Get first value from filtering an observable array

假设我有一个 observable 数组,其结构如下:

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

我想取出a不为null的第一个对象。 我怎样才能返回{a: [1,2,3,4]}

你可以试试这样的

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)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM