【问题标题】:Filter an Array of Objects from an Array in TypeScript从 TypeScript 中的数组中过滤对象数组
【发布时间】:2020-02-04 04:06:24
【问题描述】:

我构建了一个自定义组件来过滤一组对象。过滤器使用按钮,从活动设置为非活动,并允许同时打开/关闭多个选项。

我尝试的 StackBlitz - https://stackblitz.com/edit/timeline-angular-7-ut6fxu

在我的演示中,您将看到北、南和东的 3 个按钮/选项。通过单击一个,您可以将其激活,结果应该包括或排除匹配的“位置”,无论是北、南还是东。

我已经创建了我的方法和结构来进行过滤,我正在努力解决最后的逻辑。

到目前为止,我已经创建了一个方法来创建过滤位置数组,具体取决于用户从 3 个按钮中单击的内容。

接下来,这将传递给我的“过滤器数组”,它获取应该将此过滤后的数组与原始数组进行比较的逻辑,以带回仍然剩余的结果数组。

它不太好用,也不知道为什么 - 我最初是通过使用管道来实现这个功能的,但出于某种原因不想朝那个方向发展。

//the action
  toggle(location) {
    let indexLocation = this.filteredLocations.indexOf(location);

    if (indexLocation >= 0) {
      this.filteredLocations = this.filteredLocations.filter(
        i => i !== location
      );
    } else {
      this.filteredLocations.push({ location });
    }
    this.filterTimeLine();
  }

// the filter
  filterTimeLine() {
    this.filteredTimeline = this.timeLine.filter(x =>
      this.contactMethodFilter(x)
    );
  }

//the logic
  private contactMethodFilter(entry) {
    const myArrayFiltered = this.timeLine.filter(el => {
      return this.filteredLocations.some(f => {
        return f.location === el.location;
      });
    });
  }

https://stackblitz.com/edit/timeline-angular-7-ut6fxu

【问题讨论】:

    标签: javascript arrays angular typescript filter


    【解决方案1】:

    对不起我的表达,但你的代码有灾难。 jajaja!.也许你失去了你需要的东西,但你的函数中的逻辑太错误了。将字符串与对象进行比较。过滤一个数组,过滤内部相同的数组......所以你需要做一些改变。

    一个:

     this.filteredLocations.push({location});
    

    您正在推动对象。你只需要推送字符串。

     this.filteredLocations.push(location);
    

    两个:

      filterTimeLine() {
        this.filteredTimeline = this.timeLine.filter(x =>
          this.contactMethodFilter(x)
        );
      }
    

    在此函数中,您过滤 timeLine 数组。在contactMethodFilter 内部,您再次调用过滤器方法到 timeLine....

    查看功能解决方案:

    https://stackblitz.com/edit/timeline-angular-7-rg7k3j

    【讨论】:

    • 一直在绞尽脑汁——第一个并不意味着把它留在那里,第二个也是一样。逻辑和返回新数组对我不起作用。谢谢朋友
    【解决方案2】:
    private contactMethodFilter(entry) {
        const myArrayFiltered = this.timeLine.filter(el => {
          return this.filteredLocations.some(f => {
            return f.location === el.location;
          });
        });
      }
    

    这个函数没有返回任何值,而是传递给.filter

    考虑根据您的逻辑返回一个布尔值。目前过滤器未定义(虚假),所有内容都将被过滤掉

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2021-08-01
      相关资源
      最近更新 更多