Property 'filter' does not exist on type 'Object'

10,957

Solution 1

filter is an array method which cannot be used for objects in your case res.

First check if res is an array.

if(Array.isArray(res)){
   this.arr = res.filter(
                res => res.id == selection.target.value);
}

Or set type to res as (res: Array<any>)

If your api is returning an object, in most cases it should be, you can't use filter method here, you should be using it for an array inside res object.

Solution 2

Either the object is null or it is not an array
try to check if the object is not null and is an array with
if(res != null && Array.isArray(res))

Solution 3

Change this line:

this.http.get(this.json_liq).subscribe(res => {

to this:

this.http.get(this.json_liq).subscribe((res: any) => {

or better yet to this:

 this.http.get(this.json_liq).subscribe((res: Array<any>) => {

and you should be able to bypass your typechecking error at the compiler.

Here is some more info from the official docs:

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist:

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

Solution 4

I think your res in not array please check type of res, if it is array then filter method work.

Share:
10,957

Related videos on Youtube

prevox
Author by

prevox

Updated on May 26, 2022

Comments

  • prevox
    prevox almost 2 years

    After updating my code to HttpClient I can't get filter() to work with the response. I keep getting Property 'filter' does not exist on type 'Object':

    TS:

    liqOnChange(selection): void  {
            this.http.get(this.json_liq).subscribe(res => {
                this.arr = res.filter(
                    res => res.id == selection.target.value);
            });
    }
    
    • Mark
      Mark over 5 years
      Filter is an array method. Is res an array?
  • prevox
    prevox over 5 years
    The problem came from the API, thanks for pointing that out. I was sure that I was getting an array but after checking like u said and setting the type to array without success I realized that I was getting an object with an array inside.
  • Lasithe
    Lasithe over 5 years
    @prevox no problem