Error: The function `filter` is not a valid method of `states` object in the `searchStates` function

[
    {
        "abbr": "AL",
        "name": "Alabama",
        "web": "www.google.com",
        "capital": "Montgomery",
        "lat": "32.361538",
        "long": "-86.279118"
    },
    {
        "abbr": "AK",
        "name": "Alaska",
        "capital": "Juneau",
        "lat": "58.301935",
        "long": "-134.419740"
    },
    {
        "abbr": "AZ",
        "name": "Arizona",
        "capital": "Phoenix",
        "lat": "33.448457",
        "long": "-112.073844"
    },
    {
        "abbr": "AR",
        "name": "Arkansas",
        "capital": "Little Rock",
        "lat": "34.736009",
        "long": "-92.331122"
    },
    // Additional state data here
]

My code retrieves data from a local JSON file without any errors, however when attempting to fetch data from an external URL, I encounter a "TypeError: states.filter is not a function" in my searchStates function. How can I successfully filter and manipulate data fetched from an external URL? Though I am able to log the content of the .json file retrieved from the external source using console.log, filtering the data is resulting in this error.

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');

const searchStates = async searchText =>{
    

    let url = 'https://exampleurl.json';
    let res= await fetch(url);

    let states= await res.json();


    let matches=states.filter(state => {
        const regex = new RegExp(`^${searchText}`,`gi`);
        return state.name.match(regex) || state.abbr.match(regex);
    });

    if(searchText.length === 0){
        matches=[];
        matchList.innerHTML='';
    }

    outputHtml(matches);    
};

const outputHtml = matches => {
    if(matches.length > 0) {
        const html=matches.map(match => `
            <h4>${match.name} (${match.abbr}) <a href="https://${match.web}/">Visit example.com!</a></h4>
        

        `).join('');

        matchList.innerHTML = html;
    }


}


search.addEventListener('input', () => searchStates(search.value));

Answer №1

Your query results in JSON that doesn't match the data returned by the API.

One possible solution is to utilize states.items.filter instead of states.filter. However, it's important to note that the API does not contain a property named abbr, so attempting to access it will result in an undefined value:

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');

const searchStates = async searchText => {


  let url = 'https://v1.nocodeapi.com/emrescksn/webflow/WAOOrnxdScaWCRlT';
  let res = await fetch(url);
  //let res= await fetch('../json/states.json');
  let states = await res.json();

  let matches = states.items.filter(state => {
    const regex = new RegExp(`^${searchText}`, `gi`);
    return state.name.match(regex);
  });

  if (searchText.length === 0) {
    matches = [];
    matchList.innerHTML = '';
  }

  outputHtml(matches);
};

const outputHtml = matches => {
  if (matches.length > 0) {
    const html = matches.map(match => `
            <div class="card card-body mb-1">
            <h4>${match.name} (${match.abbr}) <a href="https://${match.web}/">Visit W3Schools.com!</a></h4>
            </div>

        `).join('');

    matchList.innerHTML = html;
  }


}


search.addEventListener('input', () => searchStates(search.value));
<input type="text" id="search">
<div id="match-list"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery - Issue encountered when attempting to hide dropdown during change event

Hey there, I am trying to create a new dropdown menu that changes according to the selected values in another dropdown. Currently, I am able to display the dropdown menus based on selection, but I cannot figure out how to hide the other dropdowns when a di ...

Transforming a file with a node module that lacks a .js class into a browseable format

I am currently working on browserifying my module. One of the dependencies I have is on this https://www.npmjs.com/package/chilkat_win32. It is present in my node_modules folder and here is how the structure looks: https://i.stack.imgur.com/uw9Pg.png Upo ...

Looping through data returned from Ajax call and displaying it as HTML in CodeIgniter using JQuery

Just dipping my toes into the world of JQuery AJAX, here's what I've got so far: $(document).ready(function() { $("#city").change(function() { var city_id = $("#city").val(); if (city_id != '') { $.ajax({ type ...

Assigning a changing label to a radio button

Looking to create a dynamic form where clicking a button calls a JavaScript function. Here's the code snippet: function addRadioButton(type){ var element = document.createElement("input"); //Set attributes for the element. element.setAttr ...

Encountering issues decoding JSON on android platform

I'm facing a challenge with Android and can't seem to figure out why this exception is happening while parsing JSON. Any help or alternative suggestions would be greatly appreciated. The JSON file containing a list of all countries with their ci ...

AngularJS toaster doesn't seem to be appearing

I have integrated the angularjs toaster library into my project. Here are the necessary references: https://github.com/jirikavi/AngularJS-Toaster Added the following references for the library: <link rel="stylesheet" href="bower_components/Angu ...

TagManager in Android fails to retrieve default values

Having some issues implementing the Android TagManager from Google. Struggling to load default values. Created a default json file: assets/tagmanager/GTM-xxx.json Contents of the file: { 'eulaTextVersion': '1' } Added code to pull ...

Fixing the GLTF Loader Error in Vue JS: Troubleshooting the issue of 'No loaders configured'

I am attempting to integrate a gltf file into a Vue project. Below is the code I have been working on: import * as THREE from 'three' import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; let scene, camera, renderer; fu ...

Executing a TypeORM query with a distinct clause that ignores case sensitivity

I am attempting to construct a TypeORM query builder that pulls data from a postgresql database to retrieve all unique names. Here is how my query currently looks: names = await this._context.manager .getRepository(Names) .createQueryBuilde ...

Using Three.js to load a JSON model and easily implement it in multiple instances

Is there a way to load a JSON model just once and then add it multiple times to the scene with different scales, positions, etc? I've tried adding the Object3D() to an array, assigning a position and scale to each object in the array, adding them to ...

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

What is the method for stopping a slide in this script?

Welcome everyone! Check out this piece of code I have: <script type="text/javascript" > $(function(){ var time = 10000;//milliseconds var index = 0; var container = $("#containerr"); var child ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

The JavaScript function may fail to work if the AJAX request is not completed

Upon completion of my ajax request, my function does not seem to be functioning as expected. Here is the script I am using: <script> function sendmsg(id,msg){ alert('id is'+id+'and msg is '+msg); } <scr ...

Selecting multiple elements with the same attribute value using jQuery

I am looking to target specific DOM elements using jQuery. Below is the HTML code: <li> <span class="node> <span class="con"></span> <span class="check"></span> <img> <a title="high">abc&l ...

Injecting jQuery into an Angular 1.5 component: Step-by-step guide

I'm eager to understand how to incorporate jQuery into a component. Take for instance Within my webpack configuration file: new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }) In the file of my component: ...

determining the sorting behavior of columns in Datatables

While working on my table, I referred to a Datatbles tutorial that covers sorting the third column as a percentage value. // Setting up column search - adding a text input to each footer cell $('#p_table-id tfoot th').each(function ...

What sets the screen property apart from the window property?

I'm working on a Web application and I need to access the browser window's Height & Width. Initially, I used JavaScript properties Screen.Width , Screen.Height to get these values. Later on, I came across another property called Window.Width , Wi ...

Struggling with Conditional rendering in React JS - Need help!

I am currently working on a web application that fetches product/data from a backend API and displays it on the frontend. I am also implementing an 'add to cart' and 'remove from cart' functionality. My goal is to display 'add to c ...

Exploring methods to conduct testing on an AngularJS application using AngularJS end-to-end testing, specifically focusing on scenarios involving multiple inputs

Our program includes a directive that is repeated multiple times with an input field. The structure of our code resembles the following: <li> <label>AMI</label> <div class="searchbox" searchbox="" filter="search.ami"> ...