【问题标题】:How to filter out array of elements from array of object via rxjs如何通过rxjs从对象数组中过滤出元素数组
【发布时间】:2020-08-19 10:02:35
【问题描述】:

我有两个数组,我的主数组在这里

 let main=[
        { name:'someone',category:[1,45,67]},
        { name:'someone',category:[1,25,127]},
        { name:'someone',category:[1,89,127]}
     ]

我想根据 category 对其进行过滤,这是我想要从主数组中获得的类别数组

   let Categoryfilter=[45,25]

结果应该在过滤器之后

        [
        { name:'someone',category:[1,45,67]},
        { name:'someone',category:[1,25,127]}
        ]

【问题讨论】:

  • 这似乎更像是 ES6 或打字稿问题?

标签: angular rxjs


【解决方案1】:

这是来自 rxjs 文档的稍微修改的版本: https://www.learnrxjs.io/learn-rxjs/operators/filtering/filter

import { from } from 'rxjs';
import { filter } from 'rxjs/operators';

const source = from([        { name:'someone1',category:[1,45,67]},
        { name:'someone2',category:[1,25,127]},
        { name:'someone3',category:[1,89,127]}]);
let Categoryfilter=[45,25]

const example = source.pipe(
  filter(
    person => 
      !!person.category.find((catnum) => Categoryfilter.includes(catnum))
  )
);

const subscribe = example.subscribe(val => console.log(val.name));

我不确定它是否有效。

【讨论】:

    【解决方案2】:

    没试过,但也许我可以给你一个想法?

    const filteredArray = main.filter(element =>
    element.category.some(number => categoryFilter.indexOf(number) > -1))
    

    【讨论】:

    • 我想要 rxjs
    【解决方案3】:

    您可以使用内置过滤功能

    const filtered = main.filter(item => item.category.includes(45) || item.category.includes(25));
    

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2021-10-28
      • 1970-01-01
      • 2019-01-17
      • 2022-12-12
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多