The loop does not seem to be cycling through every item in the JSON dataset

In the JSON dataset provided, there seems to be an issue with the loop only iterating through the first pokemon, Bulbasaur. When typing in names of other pokemons such as "Ivysaur" or "Venusaur", it simply shows "Not found". Take a look at the code snippet below for reference.

    let findpokemongame = {https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json} //click the link to find the JSON dataset

        var findname = window.prompt("Enter Pokemon Name")
let checkname = function(findname, findpokemongame) {
  for (let thispokemon in findpokemongame.pokemon) {
    if (findpokemongame.pokemon[thispokemon].name == findname) {
      let pokemondetails = findpokemongame.pokemon[thispokemon];
      console.log(pokemondetails);
      for (info in pokemondetails) {
        if (typeof pokemondetails[info][0] === 'object') {
          pokemondetails[info] = pokemondetails[info].map(o => o.name)
        }

        alert(info + " : " + pokemondetails[info] + "\n")

      }
    }
    else{
      alert('Not found');
      break;
    }
  }
}

checkname(findname, findpokemongame)

Answer №1

I recommend using array.find to simplify your code if it's currently very nested and complex. By finding the pokemon first, you can then perform additional operations on it, making any errors more obvious:

const foundPokemon = findpokemongame.pokemon.find(pokemon => pokemon.name === findname);

// check foundPokemon
if (foundPokemon) {
  // extract details once Pokemon is found
} else {
  // handle case when Pokemon name is not found
}

To ensure consistency in handling names, consider converting both user input and JSON data pokemon names to lower case using (string.toLowerCase()) before comparing them.

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

Converting Text to JSON

I need assistance with converting a set of data into JSON format. Below is the current format: Text Data 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4 192.168.0.5 192.168.0.6 192.168.0.7 192.168.0.8 192.168.0.9 I want to convert this data into JSON lik ...

Trigger form submission upon file upload via ajax

I am struggling with submitting a form to upload a file using AJAX. My main issue is sending the temporary path to PHP and then receiving an array as a response. Essentially, my goal is to submit the form, retrieve the temp path, pass it to PHP through JS ...

Navigating through different views in a Vue application using Vue Router directly from Vuex actions

Currently, I am in the process of developing a web application using Vue 2.x and Vuex 2.x. In this project, I need to retrieve some data from an external source via an http call. If this call fails, my objective is to redirect to a different page. GET_PET ...

Enhancing input value by incorporating selected options from multiple choices

I am working with 2 select boxes. <select id="field1" class="inputtextbox required" size="0"> <option value="Student">Student</option> <option value="Teacher">Teacher</option> <option value="Director">Director</optio ...

Upon first render, useSession from Next Auth does not retrieve the session

I am currently working on a project to create a website using NextJS v13 and Next Auth v4. However, I have encountered an issue where the session is not returned in the initial render when utilizing the useSession hook. As a result, several components are ...

What could be causing the issue with file_get_contents not loading the phpscript correctly in this scenario?

In my coding experience, I created a piece of code that essentially accomplishes the following: <div id="thisDiv"> </div> <?php echo "<script>document.getElementById('thisDiv').innerHTML = '".addslashes(str_replace(arr ...

Tips for parsing nested JSON arrays with Python?

Is there a way to extract the accountNumber, name, and phoneNumber values separately from a JSON response using Python? [{ "msg": "result", "id": "testdata", "result": [{ "accountNumber": "123456", "name": "CHRISfarmece", ...

Creating a feature that uses a button press to initiate an Ajax request based on a specific identifier

I'm looking for the most efficient way to structure a page that involves making Ajax calls. My main issue lies in setting up the event binding for when a user clicks a button. I'm struggling to find a method to pass the ID to the function that t ...

Display a still image in cases where the browser does not support 3D images

I need to display a 3D image in my HTML page if the browser supports canvas, otherwise I want to show a static image. The image should be loaded dynamically when the page loads. <!DOCTYPE html> <html class="no-js" lang="en"> <head> ...

What is the best way to refresh resources after the state of the Admin component has been updated?

My approach to dynamically obtaining resources through a function was working well until I encountered an issue with changing screen sizes. I believed that by adding a state called "screenSize" in the admin component and updating it upon resize, I would ...

Authentication in HTML5 beyond the internet connection

Seeking feedback on the most effective way to control access to an HTML5 application that is primarily used offline. This application utilizes IndexedDB, local, and session storage to securely store data for offline use, all served via HTTPS. The main go ...

How can you configure the terminal in Visual Studio Code to automatically display a custom name for each terminal window opened?

I find myself working on multiple projects simultaneously, each with its own terminal. How can I easily identify which terminal corresponds to each project? Take a look at the image below. I would like to customize the naming system of these terminals so ...

Differences between count() and length() methods in Protractor

When it comes to determining the number of elements inside the ElementArrayFinder (which is the result of calling element.all()), you have two options according to the documentation: $$(".myclass").length, detailed here: This approach involves using ...

What steps can be taken to resolve the issue of "Uncaught TypeError: undefined is not a function"?

Check out the JSfiddle link for reference: http://jsfiddle.net/mostthingsweb/cRayJ/1/ Including my code below along with an explanation of what's going wrong: This is a snippet from the HTML header, showing all the necessary links: <head> ...

Loading images incrementally using promises

Attempting to load images with different resolutions sequentially using promises. Even after making changes as per the first suggestion, only one image is getting loaded according to Chrome dev tools. function loadImage(src) { return new Promise(fun ...

NodeJS encountered a SyntaxError while trying to export the 'routes' object as

const paths = (app) => { app.route('/contact') .get((req, res, next) => { // middleware console.log(`Request from: ${req.originalUrl}`) console.log(`Request type: ${req.method}`) next(); }, (req, res, next) = ...

Avoid binding an object in Vue.js when you intend to copy it to a different data attribute

I am facing a situation where I have an object retrieved from my API and need to replicate it to another object while loading a modal. The following method achieves the duplication: this.servicesForm.services = this.team.services; // New object ...

Javascript Interval Not Triggering Function Update

I have a script that checks the number of unread records for notifications. When I use this code, the page displays the number at the time the page loads: $(document).ready(function(){ $("#notes_number").load("getnumber.php"); }); However, I am attemp ...

Nextjs: If you encounter a file type that requires special handling, make sure you have the necessary loader configured to process it. Otherwise, the file will

I encountered the following error while attempting to run my Next.js application: ./node_modules/canvas/build/Release/canvas.node Module parse failed: Unexpected character '' (1:2) You may need an appropriate loader to handle this file type, curr ...

Anticipate the moment when a variable will shift

Before proceeding to the next step, I have an observable that must be executed. export class MyExample implements OnInit { flag; constructor(private myService: MyService) { } myFunc() { flag = 0; this.myService.subscribe(data ...