An issue has been discovered with the Search function as JavaScript's Array.filter() and .map() methods are not functioning properly, resulting in

Currently, I'm working on integrating a search feature into my Flask application that will display the cities entered by users and are present in the JSON API results of a weather API.

I am following a tutorial and have used a code similar to this: https://codepen.io/jamesqquick/pen/XWJxBQv

However, when implementing it, the .filter() and .map() functions seem to be causing an error. The specific error message is as follows: TypeError for map() and filter()

How can I resolve this issue?

Below is the code snippet (the regular generateHTML section at the beginning with fetching current weather data is functioning correctly, only the "SEARCH BAR" part is encountering issues):

let currentType = "current.json";
let userCity = "London";

const apiData = {
    url: "http://api.weatherapi.com/v1",
    type: `${currentType}`,
    key: "40cd513af8aa446484a92837213011",
    city: `${userCity}`,
  };


const { url, type, key, city } = apiData;

const apiUrl = `${url}/${type}?key=${key}&q=${city}`;

console.log("apiUrl:");
console.log(apiUrl);

 fetch(apiUrl)
   .then((data) => {
     if (data.ok) {
       return data.json();
     }
     throw new Error("Response not ok.");
   })
   .then((locationRequest) => generateHtml(locationRequest))
   .catch((error) => console.error("Error:", error));

 const generateHtml = (data) => {
   console.log("data:")
   console.log(data);
   console.log("data.location.name:")
   console.log(`${data.location.name}`);
   const html = `
     <div class="weather-location">
        <h1>${data.location.name}, ${data.location.country}</h1></div>
     <div class="details">
         <span>Tmp: ${data.current.temp_c} °C</span>
         <span>Feels like: ${data.current.feelslike_c} °C</span>
     </div>
 `;
   const weatherDiv = document.querySelector(".weather");
   weatherDiv.innerHTML = html;
};
/* SEARCH BAR */

const citiesList = document.getElementById('weather-cities');
const searchBar = document.getElementById('weather-searchbar');
let cities = [];

console.log("citiesList:");
console.log(citiesList);
console.log("searchBar:");
console.log(searchBar);

searchBar.addEventListener('keyup', (e) => {
    userCity = e.target.value.toLowerCase();
    console.log("usercity:");
    console.log(userCity);
    const filteredCities = cities.filter((city) => {
        return (
            city.name.toLowerCase().includes(userCity) ||
            city.region.toLowerCase().includes(userCity) ||
            city.country.toLowerCase().includes(userCity)
        );
    });
    displayCities(filteredCities);
});

const loadCities = async () => {
    try {
        currentType = "search.json";
        const res = await fetch(apiUrl);
        cities = await res.json();
        console.log("cities:");
        console.log(cities);
        displayCities(cities);
    } catch (err) {
        console.error(err);
    }
};

const displayCities = (cities) => {
    let htmlString = cities
        .map((city) => {
            return `
            <li class="character">
                <h2>${city.location.name}</h2>
                <p>Temperature: ${city.current.temp_c} °C</p>
                <p>Feels like:${city.current.feelslike_c} °C></p>
            </li>
        `;
        })
        .join('');
    citiesList.innerHTML = htmlString;
};

loadCities();
<div class="other-stats">
    <div class="weather-search">
      <input type="text" id="weather-searchbar" placeholder="Your city"></input>
      <ul id="weather-cities"></ul>
    </div>
    <div class="weather"></div>
  </div>
  <script src="../static/weather_api.js"></script>

Answer №1

When working with arrays, it is common to use Array.prototype.filter() and Array.prototype.map(). However, in this case, we are dealing with a JavaScript object that contains city data. To properly store the list of cities, make sure to assign an array to the "cities" property.

Answer №2

Great news! I have managed to resolve the issue at hand. While working on the displayCities function, I realized that in the HTML section, instead of using city.location.name as I would normally do for retrieving the name from the "current.json" API call, I needed to use city.name for the new API call "search.json" which returns an array of dictionaries with direct information without categorization like "location" or "current". For a clearer explanation, take a look at the console.log entries below:

API call "current.json"

API call "search.json"

const displayCities = (cities) => {
    let htmlString = cities
        .map((city) => {
            return `
            <li class="character">
                <p>${city.name}</p>
            </li>
        `;
        })
        .join('');
    citiesList.innerHTML = htmlString;
};

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

What is the best way to extract the lodash score from a URL using JSON parsing?

Can someone help me figure out how to extract and store the names from a URL into an array, then parse JSON data to retrieve the lodash score and convert it into a whole number? Any assistance would be greatly appreciated. <head> <title> ...

When an attempt to make a POST request using fetch() is made, a TypeError: Failed to fetch error is immediately thrown instead of

My front-end form is posting data using the fetch() function. Everything works fine and I get the correct response from the server when it runs smoothly without any interruptions. However, when I debug the server endpoint, it throws a TypeError: failed to ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Run the Ionic function only when the app is launched for the first time

I'm facing an issue with a function in Ionic storage that sets an array to default values. I only want this function to run the first time the app is launched on a user's phone, but currently it runs every time the app is opened because it's ...

Update in slide height to make slider responsive

My project involves a list with text and images for each item: <div class="slider"> <ul> <li> <div class="txt"><p>First slogan</p></div> <div class="img"><img src="http://placehold.it/80 ...

Creating a dynamic input box with an add/remove button in each row using jQuery

Need help with a jQuery-based UI that allows users to dynamically add input boxes. The desired look is as follows: Default appearance: INPUT_BOX [ADD_BUTTON] [REMOVE_BUTTON] Clicking on the [Add_Button] should add another row like this, and so on: ...

In order to modify the PHP code in the file, I will need to update the JSON output that is currently being generated

I am currently using PHP code to generate a JSON output, but I have encountered an issue where it's creating an array of arrays with the information. What I want is to eliminate one array and simply display the list of APIs that have been used along w ...

Bringing in data using .json files in a react native environment with Redux

I have developed a fitness app and I am utilizing Redux to store all the sets and workouts. Currently, I have manually entered all the exercises into Redux data for testing purposes. However, I now have all the exercises stored in a .json file and I want t ...

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

Filtering multiple custom post types in Wordpress with custom taxonomies using Ajax results in the issue where newly created posts are not displayed in the response

Update: I just figured out the solution to my own problem. If anyone can assist in adding pagination to the response, I'd be happy to treat you to a pint of your choice! :) There's some code that needs tidying up here, but I'll get to it lat ...

Ways to efficiently transmit pre-designed HTML components from a WebMethod to jQuery

I'm currently working on implementing infinite scrolling on my ASP.NET C# Website. In the past, I used a somewhat cumbersome method involving the ListView Control to achieve lazy scrolling, but I'm looking for a more efficient solution this time. ...

Tailwind does not display font sizes using random values

I am attempting to adjust the size of a span element based on a number from a variable: export default async function Tags() { const tags = await getTags(); return ( <div> <Suspense> <div className="flex flex-wrap ...

VueJS: Send all unspecified attributes to child component in the same way as using v-bind="$props"

I am looking for a way to receive any props passed by the parent component into the child component without explicitly mentioning them in props:[]. This is because I may not always know which props will be bound. Parent component <template> <di ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

Failed to retrieve Json data from the designated remote url

I have been trying to figure this out for hours. I'm struggling to retrieve the JSON data from a remote REST API. My goal is to fetch the JSON data and display the "html_url" field from it on my website. <html> <head> ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...

Fade in images using jQuery

I am having issues with fading in and out images using jQuery, it doesn't seem to be working as expected. I think there might be something crucial that I am missing. Take a look at the script below: var count = 1; setInterval(function() { ...

Is it possible to add a personalized parameter to an unnamed JavaScript replace function?

I am looking to customize a date value in the following format: var d = new Date(); myobj.format(d, "dddd (ddd) S dd'd'.MM (MMM MMMM).yyyy HH:mm:ss.fff t tt T TT (o) {Z}"); I prefer not to utilize date.js because of its large size. The issue ...

Angular: presenting items in navigation bar post logging in

I am relatively new to AngularJS and I am experiencing difficulties in displaying the userInfo in my navbar and showing the Logout button only when I am logged in. 1) Currently, I am using ng-show to show the Logout button only when I am logged in, but t ...

From navigating getElementByID to tackling getElementsByClassName while constructing multiple select elements: a guide

I am facing an issue with accessing multiple select elements that have the same options in Javascript. Despite having the same class, I am unable to retrieve the options using Javascript. When I attempted switching from getElementById to getElementsByClass ...