在键值对内的数组中过滤特定值

时间:2019-01-25 06:40:16

标签: javascript ecmascript-6

我需要从给定对象中根据用户输入过滤城市。

我有一个对象:

arr= [
    {'country':'india','cities':['bangalore','chennai']},
    { 'country': 'USA' , 'cities': ['New yourk','Chicago'] }
  ]

默认情况下,它将以html显示每个国家和地区和值。当用户在输入中输入值时,我只需要显示与输入匹配的“城市”即可。

这是链接:
https://stackblitz.com/edit/angular-pxaa7b?file=src%2Fapp%2Fapp.component.ts

当有人开始输入内容时,我需要显示与用户输入匹配的城市结果。

3 个答案:

答案 0 :(得分:1)

filteredArray = input.valueChanges.pipe(
 map(inputValue => arr.filter(arrValue => arrValue.startsWith(inputValue)))
);

并在filteredArray上使用异步管道。

答案 1 :(得分:1)

尝试一下:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  display = [];
  arr = [
    { 'country': 'india', 'cities': ['Bangalore', 'Chennai'] },
    { 'country': 'USA', 'cities': ['New York', 'Chicago'] }
  ]
  name = 'Angular';
  constructor() {
    this.display = this.arr;
  }


  search(e) {
    let input = e.target.value.toLowerCase();
    // this.display = input ? this.filter(input) : this.arr;
    this.display = input ? this.filterByArrayMethods(input) : this.arr;
  }

  filter(val) {
    let res = [];
    this.arr.forEach(countryObj => {
      const countryToAdd = {
        country: countryObj.country,
        cities: countryObj.cities.filter(city => city.toLowerCase().includes(val))
      };
      if(countryToAdd.cities.length > 0) {
        res.push(countryToAdd);
      }
    });
    return res
  }

  filterByArrayMethods(val) {
    return this.arr.reduce((accumulator, countryObject) => {
      const citiesInTheCountry = countryObject.cities.filter(cityName => cityName.toLowerCase().includes(val));
      if (citiesInTheCountry.length > 0) accumulator.push({ ...countryObject, cities: citiesInTheCountry })
      return accumulator;
    }, []);
  }


}

  

这是您推荐的Working Sample StackBlitz

答案 2 :(得分:1)

在您的特殊情况下,我应该检查一下您的堆栈闪击:

res=this.arr.map(e=>({...e, cities: e.cities.filter(city => city.toLowerCase().indexOf(val.toLowerCase()) > -1)}))