javascript 如何通过在输入中搜索来过滤数组数据

kx5bkwkv  于 2022-12-25  发布在  Java
关注(0)|答案(3)|浏览(161)

如何过滤输入文本中的数组对象-Angular 我正在尝试做一个搜索栏来过滤用户可以搜索的位置/描述,我将其命名为“传感器”。

房间列表.组件.ts

validateForm: FormGroup;
  rowData: templogRecord[] = [];
  option: any = [];

  onLoad() {
    this.rowData = record.default.records;

    this.option = [];

    this.rowData.forEach(room => {
      this.option.push({
        tooltip: {
          formatter: "{a} <br/>{b} : {c}°"
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: false },
            restore: { show: false },
            saveAsImage: { show: false }
          }
        },
        series: [
          {
            name: room.sensor,
            type: 'gauge',
            center: ['40%', '70%'],
            splitNumber: 10,
            radius: '70%',
            axisLine: {
              lineStyle: {
                color: [[0.2, '#48b'], [0.8, '#228b22'], [1, '#ff0000']],
                width: 8
              }
            },
            axisTick: {
              splitNumber: 10,
              length: 12,
              lineStyle: {
                color: 'auto'
              }
            },
            axisLabel: {
              textStyle: {
                color: 'auto'
              }
            },
            splitLine: {
              show: true,
              length: 30,
              lineStyle: {
                color: 'auto'
              }
            },
            pointer: {
              width: 5
            },
            title: {
              show: true,
              offsetCenter: [0, '65%'],
              textStyle: {
                fontWeight: 'bolder'
              }
            },
            detail: {
              formatter: '{value}°',
              textStyle: {
                color: 'auto',
                fontWeight: 'bolder'
              }
            },
            data: [{ value: this.tempGenerator(), name: "Temperature" }]
          },
          {
            name: '转速',
            type: 'gauge',
            center: ['70%', '25%'],
            splitNumber: 10,
            radius: '40%',
            axisLine: {
              lineStyle: {
                width: 8
              }
            },
            axisTick: {
              length: 12,
              lineStyle: {
                color: 'auto'
              }
            },
            splitLine: {
              length: 20,
              lineStyle: {
                color: 'auto'
              }
            },
            pointer: {
              width: 5
            },
            title: {
              show: true,
              offsetCenter: [0, '80%'],
              textStyle: {
                fontWeight: 'bolder',
              }
            },
            detail: {
              formatter: '{value}%',
              offsetCenter: [0, '55%'],
              textStyle: {
                color: 'auto',
                fontSize: 18,
                fontWeight: 'bolder'
              }
            },
            data: [{ value: 1.5, name: "Humidity" }]
          }
        ]
      });
    });
  }

  tempGenerator() {

    var time = 12;

    var num = Math.random() * 100;

    var tempBase = Math.round(num);

    var fluc = [0, 1, 1, 2, 1, 1, 2.5, 3.5, 1, 1, 1, 1,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];

    return tempBase * fluc[time];
  }

  searchData(searchValue: any) {
    if (searchValue.length >= 3) {
      this.rowData = this.rowData.filter((data: templogRecord) => {
        console.log(data['sensor']);
      });
    } else if (searchValue.length < 1) {
      console.log('empty')
    }
 }
}

房间列表. json

{
    "records": [
        {
            "dateandtime": "2018-06-14 02:24:02",
            "sensor": "Nine Seal Area",
            "temperature": "25.9",
            "humidity": "99.9"
        },
        {
            "dateandtime": "2018-06-14 02:24:02",
            "sensor": "Ten Line2",
            "temperature": "25.9",
            "humidity": "99.9"
        },
        {
            "dateandtime": "2018-06-14 02:22:01",
            "sensor": "Eight Line1",
            "temperature": "25.9",
            "humidity": "99.9"
        }
    ]
}

房间列表.组件.html

<div class="flex-container">
    <div class="date-filter">
      <nz-input-group [nzSuffix]="suffixIconSearch">
        <input type="text" 
          nz-input placeholder="Search" 
          [(ngModel)]="filterSearch" 
          (ngModelChange)="searchData($event)"
          />
      </nz-input-group>
      <ng-template #suffixIconSearch>
        <i nz-icon nzType="search"></i>
      </ng-template>
    </div>
    <ul class="cards">
      <li class="cards__item" *ngFor="let data of option">
        <div class="card">
          <div echarts [options]="data" [autoResize]="true"></div>
          <div class="card__content">
            <button class="btn btn--block card__btn">Button</button>
          </div>
        </div>
      </li>
    </ul>
  </div>

searchData函数中,我尝试让它在输入位置/描述(我将其命名为“sensor”)时进行过滤。

c90pui9n

c90pui9n1#

每次进行搜索时,都是在过滤数组中的元素,并将结果输出给原始数组,结果会丢失数据,为什么不创建两个变量呢?
1.原始数组没有改变(包含您的数据),它应该在提供程序中,但在我们的示例中,我们将在组件中声明它。
1.你要显示的过滤数组

searchData(searchValue: any) {
      this.filteredData = this.rowData.filter((item: templogRecord) => {
        return item.sensor.toLowerCase().includes(searchValue.toLowerCase());
      });
 }
ar7v8xwq

ar7v8xwq2#

我推荐此解决方案(基于材料自动完成:https://stackblitz.com/angular/lndebkoyare?file=app%2Fautocomplete-filter-example.ts
在您的组件中:

import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

/**
 * @title Filter autocomplete
 */
@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css'],
})
export class FilterExample implements OnInit {

  // your control for input
  searchControl = new FormControl();

  // your whole set of options
  options: string[] = ['One', 'Two', 'Three'];

  // your current result based on filters input
  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.searchControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.options.filter(option => option.toLowerCase().includes(filterValue));
  }
}

您的模板将如下所示:

<div class="flex-container">
<div class="date-filter">
  <nz-input-group [nzSuffix]="suffixIconSearch">
    <input type="text" 
      nz-input placeholder="Search" 
      [formControl]="searchControl"
      />
  </nz-input-group>
  <ng-template #suffixIconSearch>
    <i nz-icon nzType="search"></i>
  </ng-template>
</div>
<ul class="cards">
  <li class="cards__item" *ngFor="let data of filteredOptions | async">
    <div class="card">
      <div echarts [options]="data" [autoResize]="true"></div>
      <div class="card__content">
        <button class="btn btn--block card__btn">Button</button>
      </div>
    </div>
  </li>
</ul>

每次输入值改变时,searchControl上的可观察值valueChanges会发出该输入字段的当前值。这部分map(value => this._filter(value))返回选项数组的一个过滤子集。可以使用异步管道显示:<li class="cards__item" *ngFor="let data of filteredOptions | async">...</li>

91zkwejq

91zkwejq3#

    • 请勿使用findincludes,因为Internet Explorer不支持它们。**

使用javascript的filter函数怎么样?请看下面的例子。
下面的示例假定您的目标是对象中的sensor元素。
Click here for a DEMO

const test = {
    "records": [
        {
            "dateandtime": "2018-06-14 02:24:02",
            "sensor": "Nine Seal Area",
            "temperature": "25.9",
            "humidity": "99.9"
        },
        {
            "dateandtime": "2018-06-14 02:24:02",
            "sensor": "Ten Line2",
            "temperature": "25.9",
            "humidity": "99.9"
        },
        {
            "dateandtime": "2018-06-14 02:22:01",
            "sensor": "Eight Line1",
            "temperature": "25.9",
            "humidity": "99.9"
        }
    ]
};

let found = [];
const searchTerm = 'Eight Line1';
found = test.records.filter(function(element) {
  return element.sensor.toLowerCase() == searchTerm.toLowerCase();
});

console.log('found ' , found[0]);
    • 更新**

要执行部分搜索(搜索字符串的一部分),可以安全地使用indexOf。请参阅下面的示例,

console.log("Eight Line1".indexOf("Ei") !== -1);

希望这能帮上忙,
谢谢。

相关问题