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 process for creating an xpath for hyperlinks with the 'contains text' attribute?

I am in need of creating Xpath for links based on contained text. I have devised the following code to achieve this, however, a scenario arises when there are three links named 'Entity', 'Entity Type', and 'Entity Group'. If I ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

How to turn off automatic formatting in CKEditor

Whenever data is entered into a field using CKEditor, the Save button becomes enabled. However, if I programmatically set data into the field using Javascript, the Change event always triggers causing the Save button to remain enabled even if the field is ...

Customize the formatting of linked locale messages in Vue's internationalization (i18n) feature using parameters

Is there a way to link locale messages in vue-i18n with a parameter? { "next": "Next step {step+1}: @:steps[{step}]", "steps": [ "Welcome", // 0 "Briefing", // 1 "Finish" // 2 ...

From Python CSV to JSON: Exploring the size disparity between JSON and CSV files and possible solutions

Encountered an intriguing issue while converting a CSV file to JSON. The process involves generating a CSV file based on output from a SQLite query and saving it to the hard drive. To work with the CSV file, I use Pandas in my script: import pandas as pd ...

aws-lambda Module Not Found

I am encountering an issue in the aws-lambda console every time I try to upload code from a zip file. Oddly, other zip files seem to work fine. The .js file within the problematic zip is named "CreateThumbnail.js" and I have confirmed that the handler is ...

``There seems to be an issue with implementing the SlideDown feature in JavaScript

I am having an issue with a code where the expected behavior is to slide down a div when a person hovers over text, but it's not working. Can someone please review and identify the cause of this problem? <script type="text/javascript" src="/js/jqu ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

Tips for calculating the difference between timestamps and incorporating it into the response using Mongoose

In my attendance model, there is a reference to the class model. The response I receive contains two createdAt dates. const attendanceInfo = await Attendance.find({ student: studentId, }) .populate('class', 'createdAt'); ...

The module 'AppModule' has unexpectedly declared a value of 'Component' that was not anticipated

Recently, I've been working on transitioning my application to the new angular2 webpack rc5 setup. I have successfully generated the app module using ng cli migration. However, I am facing an issue while trying to integrate a component from my own li ...

Tips for including arguments in pm2 file execution

What steps should I take to run the cluster.js file on pm2 successfully? When I try executing the file locally with 'node cluster.js 0 1' command, it appends two arguments but encountering an error when using 'pm2 start "cluster.js 0 1"&apos ...

Transfer PHP's uniqid() function to real-time using JavaScript with jQuery

Seeking a compact JavaScript(jQuery) code snippet to achieve this: date("r",hexdec(substr(uniqid(),0,8))); Your assistance is highly appreciated. Thank you. ...

The json_encode function in Javascript is not returning a valid value

I am facing an issue with a PHP array that I encode using json_encode and then pass to a variable in a JavaScript function. Even though the array seems fine after encoding, it appears as a valid JavaScript array. However, I keep receiving 'undefined&a ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

An easy way to pass props to a component using useNavigate in React Router

Is it possible to send props directly to a component in React? const goToProjectPage = useNavigate(); useEffect(()=>{ ..... goToProjectPage("/projectpage"); //send props here },[]); ...

Executing the callback function

I am facing a situation where I have a Modelmenu nested within the parent component. It is responsible for opening a modal window upon click. Additionally, there is a child component in the same parent component that also needs to trigger the opening of a ...

Putting off the jQuery UI autocomplete focus event

Currently, I am utilizing an autocomplete feature from version 1.8.23 of the jQuery UI library. Here is a snippet of my code: $(this).autocomplete({ autoFocus: true, minLength: 2, delay: 100, source: function(request, response) ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

Loading background images in CSS before Nivo slider starts causing a problem

I've been struggling with preloading the background image of my wrapper before the nivo-slider slideshow loads. Despite it being just a fraction of a second delay, my client is quite particular about it -_- After attempting various jQuery and CSS tec ...