Angular 6 filter JSON

25,067

You are filtering the observable stream not the items array.

    return this.http.get('/assets/data/fl/' + fl + '.json').pipe(
      map(items => {
        return items.filter(items => items === 2);
      }, error => error)
    );

*the above assumes that the get request returns the array [].

Share:
25,067
Johansrk
Author by

Johansrk

Updated on July 07, 2022

Comments

  • Johansrk
    Johansrk almost 2 years

    Hi I am having trouble filtering some JSON. My console.log in my component does not show anything. I would think it would display [2]

    JSON file

    [1,2,3,4,5]
    

    Service

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { map, filter } from 'rxjs/operators';
    
    @Injectable({
      providedIn: 'root',
    })
    export class SearchFlService {
      constructor(private http: HttpClient) {}
    
      getLabels = (searchValue: string) => {
        const fl = searchValue.substring(0, 3).toUpperCase();
    
        return this.http.get('/assets/data/fl/' + fl + '.json')
          .pipe(
            filter((items) => items === 2),
            map(
              response => {
                return response;
              },
              error => error)
          );
      }
    }
    

    component

    this._searchFlService.getLabels(data.value.searchPlant)
            .subscribe(items => {
              console.log(items);
            });
    
    • user184994
      user184994 almost 6 years
      And what are you getting from it? Nothing?
  • Johansrk
    Johansrk almost 6 years
    ahh. that makes sense. It works. thanks. Though I do get this message [ts] Property 'filter' does not exist on type 'Object'.
  • Johansrk
    Johansrk almost 6 years
    I solved it by adding this "Array<number>" (res: Array<number>) => res.filter((item => item === 2),
  • sandeep
    sandeep about 4 years
    Can we put an OR (||) condition here like (items => items === 2 || items === 5) ?