过滤observable返回的对象数组的最佳方法

时间:2018-04-09 12:42:43

标签: typescript rxjs

寻找有效的方法从以下的observable返回的对象数组中只选择一个项目,并将其传递给流:

const message = of(req.body).pipe(
  .....
  .....
  filter(resp => (resp.status === 200 && resp.statusText === 'OK')),
  myFilter(resp.data.values),
  // and then continue
  tap(value => console.log(value)),
  ....
  ....    
); //end of pipe


structure of resp.data.values -> 
    [{ id: '37', createTime: '2018-03-28T09:13:07.180434550Z', name: 'tmp1'},
     { id: '38', createTime: '2018-03-28T09:14:07.180434550Z', name: 'tmp2'},
     { id: '38', createTime: '2018-03-28T09:15:07.180434550Z', name: 'tmp3'}]

代码用TypeScript 2.8.1编写,“rxjs”:“5.5.8”作为节点的后端函数。

2 个答案:

答案 0 :(得分:1)

如果您只想要一个值,并且在数组中不需要它,那么您可以使用map运算符和find的{​​{1}}方法实现该目标:

Array

当然,我假设您要按const message = of(req.body).pipe( ..... ..... filter(resp => (resp.status === 200 && resp.statusText === 'OK')), map(resp => resp.data.values.find(item => item.id === '38')), // and then continue tap(value => console.log(value)), .... .... ); //end of pipe 进行过滤,但您可以按照您想要的任何谓词进行过滤。

答案 1 :(得分:0)

如果您只想返回一个值,可以使用:

Thread Name: Test Iteration 1-1
Sample Start: 2018-04-09 14:33:01 CEST
Load time: 3006
Connect Time: 0
Latency: 0
Size in bytes: 1898
Headers size in bytes: 0
Body size in bytes: 1898
Sample Count: 1
Error Count: 1
Data type ("text"|"bin"|""): text
Response code: Non HTTP response code: java.net.NoRouteToHostException
Response message: Non HTTP response message: No route to host (Host unreachable)
Response headers:
HTTPSampleResult fields:
ContentType: 
DataEncoding: null
管道中的

而不是

first(resp => (resp.status === 200 && resp.statusText === 'OK')),

如果您想获得特定项目,可以在filter(resp => (resp.status === 200 && resp.statusText === 'OK')), 运算符的谓词函数中更精确地指定它。