Search code examples
javascriptjsonangularsearchbar

angular search bar this.items.filter is not a function


I am fetching data from a JSON file that's stored locally .The JSON string is an array of locations cities names .

{
    "data": [
      {
        "city": {
          "cityname": {
            "id": "الموصل"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      },
          {
        "city": {
          "cityname": {
            "id": "بغداد"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      }

    ]
  }

i have response in html . and all data arrays are showing , but when i searching on any city name in box search i get error :

 ERROR TypeError: this.items.filter is not a function
    at Tab1Page.push../src/app/tab1/tab1.page.ts.Tab1Page.getItems (tab1.page.ts:74)
    at Object.eval [as handleEvent] (Tab1Page.html:35)
    at handleEvent (core.js:23106)
    at callWithDebugContext (core.js:24176)
    at Object.debugHandleEvent [as handleEvent] (core.js:23903)
    at dispatchEvent (core.js:20555)
    at core.js:21002
    at HTMLElement.<anonymous> (platform-browser.js:993)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17289)

code :

 items:any


constructor() {

    this.initializeItems()

}

initializeItems() {


  this.items ={
    "data": [
      {
        "city": {
          "cityname": {
            "id": "الموصل"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      },
          {
        "city": {
          "cityname": {
            "id": "بغداد"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      }

    ]
  }
}


getItems(ev: any) {
  // Reset items back to all of the items
  this.initializeItems();

  // set val to the value of the searchbar
  const val = ev.target.value;

  // if the value is an empty string don't filter the items
  if (val && val.trim() != '') {
    this.items = this.items.filter((item) => {
      item["data"].city.cityname.id.toLowerCase().indexOf(val.toLowerCase()) > -1
      console.log(item)
    })
  }
}

Html

  <ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
  <ion-list>

    <ion-item *ngFor="let item of items.data">
      {{ item.city.cityname.id}}
    </ion-item>
  </ion-list>

any idea please ?


Solution

  • You should change :

    this.items.filter
    

    to :

    this.items.data.filter
    

    As this.items is JSON object and filter function expects array to be filtered

    WORKING DEMO ( with filter function bugs solving )