代码之家  ›  专栏  ›  技术社区  ›  cheesydoritosandkale

动态更改javascript过滤器函数内部的属性

  •  0
  • cheesydoritosandkale  · 技术社区  · 8 年前

    我想换房子 d、 姓名 d、 角色 d、 身份证 基于通过父函数传递的参数的筛选器函数内部。但我无法在过滤器函数中访问它。

       const temp = this.temp.filter(function(d) {
       return d.name.toLowerCase().indexOf(val) !== 
        -1 || !val;
        });
    

    最好的办法是什么?我做了一些调查,但似乎找不到好的解决办法。任何帮助都将不胜感激!

    3 回复  |  直到 8 年前
        1
  •  1
  •   user184994    8 年前

    您可以使用方括号语法,因此

       key = 'role'
    
       const temp = this.temp.filter((d) => {
         return d[key].toLowerCase().indexOf(val) !== 
            -1 || !val;
       });
    
        2
  •  1
  •   amrender singh    8 年前

    您可以将筛选函数包装在其他函数中,只需传入要筛选的属性名。

    例如:

    let arr = [{name :"xyz", role:"admin"},{name :"xyz", role:"teacher"},{name :"abc", role:"admin"}];
    
    function filterList(arr, prop, val){
      return arr.filter(e=> e[prop] == val);
    }
    
    console.log(filterList(arr, "role", "admin" ));
    console.log(filterList(arr, "name", "xyz" ));
        3
  •  1
  •   Community Mohan Dere    6 年前

    保持 d[keyToFilterOn] 价值 keyToFilterOn d.role .

    那么为什么不这样做呢:

    let keyToFilterOn = 'role'; // or id
    const temp = this.temp.filter(d => {
      return d[keyToFilterOn].toLowerCase().indexOf(val) !== -1 || !val;
    });
    

    这样,就不必为它创建函数。

    备选方案

    这是你的答案 filter

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
    
      transform(temp: any[], filterBy: string, filterValue: any): any {
        if (!filterBy || !filterValue) {
          return input;
        }
        return temp.filter(d => {
          return d[filterBy].toLowerCase().indexOf(filterValue) !== -1 || !filterValue;
        });
      }
    
    }
    

    使用方法如下:

    import { FilterPipe } from 'path/to/the/pipe';
    
    class YourComponent {
    
      YourFunction(value) {
        let filteredData = new FilterPipe().transform(this.temp, keyToFilterOn, val);
      }
    }
    

    Pipe 用于过滤数据。但是,由于这是在类中使用的,而不是在模板中使用的,所以没关系。