过滤可观察的数组

时间:2018-10-10 08:33:03

标签: rxjs

这是来自learningrxjs的经过编辑的示例。我想过滤类型数组中的值。但这不是它的工作方式:“由于类型'string []'和'string'没有重叠,因此此条件将始终返回'true'。”

我是rxjs的新手,无法弄清楚如何过滤数组。有什么建议吗?有可能吗?

    const source = from([
         { name: 'Joe', age: 31, type: ['a', 'b'] }, 
         { name: 'Bob', age: 25, type: ['a'] }
    ]);
    //filter out people with type b
    const example = source.pipe(filter(person => person.type != 'a'));
    //output: "People with type b: Bob"
    const subscribe = example.subscribe(val => console.log(`Type a: ${val.name}`));

1 个答案:

答案 0 :(得分:2)

您要应用的filter()带有签名为T => boolean的函数,这意味着您将必须返回布尔值true / false,以便可以从流中过滤掉元素。

您的元素T的类型为Object {name:string, age:number, type:array},因此要过滤type数组中的值,您将需要使用Array.indexOf prototype function

source.pipe(filter(person => person.type.indexOf('b') == -1) // filter out people who have type b
相关问题