【问题标题】:Array.filter() in Angular 2 ComponentAngular 2 组件中的 Array.filter()
【发布时间】:2018-04-24 10:49:53
【问题描述】:

在一个组件中,我可以使用以下内容过滤我的数组:

// Array of product objects
const result = products.filter(p => p.name.includes('val'));

产品的值与第一个值相同,但过滤后的值存储在result

但在以下代码中,filter() 过滤字符串数组本身:

// Array of strings
const result = strs.filter(s => s.includes('val'));

问题是如何在不修改strs 本身的情况下过滤字符串并返回结果?

注意:我尝试使用array.filter(function() { return res; });,但没有进行任何更改。

【问题讨论】:

  • strs.filter(s => s.includes('val')); 不会修改strs。 filter 函数返回一个新数组,其中包含您在 filter 函数中传递的谓词为 true 的项目。
  • 你的代码没问题,可能有错别字

标签: arrays angular typescript filter components


【解决方案1】:

它返回过滤的那些并且不改变实际的数组。你做错了什么

const strs = ['valval', 'bal', 'gal', 'dalval'];
const result = strs.filter(s => s.includes('val'));

console.log(strs);
console.log(result);

【讨论】:

  • 是的,你是对的,问题是因为一个对象包含另一个对象的数组。我改变了我对过滤方式的看法,它可以正常工作。谢谢
【解决方案2】:

我们需要知道的第一件事是,如果我们过滤列表,我们会丢失原始数据

products: any[] = [
 {
  "productId": 1,
  "productName": "foo-bar",
  "price": 32.99
 }
]

如果不从源中重新获取数据就无法取回它,因此我们必须创建另一个列表来存储过滤后的列表。

 filteredProduce: any[];

接下来,如果您要在网格或类似的东西上显示过滤产品列表,我们需要一种方法来了解用户何时更改过滤条件。我们可以使用事件绑定并监视按键或值的变化,但更简单的方法是将我们的 _listFilter 属性更改为 getter 和 setter,如下所示

get listFilter: string {
    return this._listFilter;
}
set listFilter(value:string) {
    this._listFilter= value;
}

接下来我们要将filteredProducts数组设置为过滤后的产品列表

set listFilter(value:string) {
    this._listFilter= value;
    this.filteredProducts = this._listFilter? this.performFilter(this._listFilter) : this.products;
}

在前面的代码中,我们使用 js 条件运算符来处理 _listFilterstring 为空、null 或未定义的可能性。 接下来我们使用this.performFilter(this._listFilter) 过滤我们的列表。

performFilter(filterBy: string): any[] {
    filterBy = filterBy.toLocaleLowerCase();
    return this.products.filter((product: any) =>
        product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}

最后,我们应该将产品的主列表分配给过滤的产品,并将 _listFilter 分配给我们想要的。

constructor() {
        this.filteredProducts = this.products;
        this._listFilter= 'foo-bar';
    }

最后一步是更改我们的模板以绑定到我们的过滤产品属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 2016-10-06
    • 2017-03-01
    • 2017-11-05
    • 2016-11-08
    • 2016-10-25
    • 1970-01-01
    相关资源
    最近更新 更多