What is the best way to compare a JSON object and a string in JavaScript?

Currently, I am working on developing the website layout for . Most of the data retrieval and display have been successful so far.

However, when attempting to filter my search results to show only stop names associated with Subways, I encountered some errors. You can find the JSON page related to this issue at . Specifically, when trying to access stops with the route name 'Yonge-University-Spadina Subway', I received an error message stating '

Uncaught TypeError: Cannot call method 'equals' of undefined
'. I also attempted using the '===' operator without success. Despite searching extensively online for a solution, I have not been able to resolve this issue. As a beginner in JavaScript, it is possible that I overlooked something crucial in my code. Here is the portion of my code causing the problem:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
      $(document).ready(function(){
        // retrieving the data.
        $.getJSON("http://myttc.ca/finch_station.json?callback=?", function(data){
          //Storing the string in variable.   
          var subway="Yonge-University-Spadina Subway";

          console.log(data);
          //Displaying the station name first in a div called "stations" in the body.
          $("#stations").append('Station: ' + data.name + '<br/>');

          //Iterating through the stops array to display each stop name 
          $.each(data.stops, function(i,stopz){

          $("#stations").append('&nbsp;&nbsp;Stop: ' + stopz.name + '<br/>');
          //This is my problem area.Not able to compare the routes.name to the string.   
          if(stopz.routes.name === subway) {
            $.each(stopz.routes, function(i,routez) {
              //Displaying the Departure time and shape of the stops.
              $.each(routez.stop_times, function(i,timez) {
                $("#stations").append('&nbsp;&nbsp;&nbsp;&nbsp;Departure-time: ' + timez.departure_time + ' || Shape: ' + timez.shape + '<br/>');  
              });
            });
            }
          });
         });
       });
     </script>

 </head>
 <body>

 <div id="stations">
 </div>
 </body>
 </html>

I would greatly appreciate any assistance provided. Thank you.

Answer №1

After reviewing the structure of your stops data:

{"routes":[],"name":"Finch Station GO Hallway","uri":"finch_station_go_hallway","agency":"Toronto Transit Commission"}

Your reference to stopz.routes.name appears to be incorrect. It seems you intended to refer to stopz.name. Therefore, your code should be adjusted as follows:

            if(stopz.name === subway)
            {
                $.each(stopz.routes, function(i,routez){
                    // ... etc ...
                });
            }

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 most effective method for utilizing v-model with a pre-populated form in Vue.js?

Need some help with a form and looping through items in a module to generate textfields. Take a look at the photo for context: Link: Currently, I'm using a structure like this... <v-row class="d-block d-md-flex"> ...

Angular not updating the values in real time

First and foremost, I am utilizing socket.io to emit data. Data is emitted upon connection (so the website does not appear blank) as well as when certain events occur. Upon initial connection or page refresh, everything updates and functions smoothly. Howe ...

How can we best optimize the conclusion of an infinite scroll when content is depleted?

Our web application has a feature that automatically loads more content when the bottom of the page is reached. Here's how it works: $window .on('scroll', function () { var $this = $(this) ; if ($this.scrollTop() == $do ...

The vue-croppa component is showing unusual behavior, with an error message stating "Failed to mount component: template or render function not

I recently tried utilizing vue-croppa for image cropping in my project. I installed it using the npm package manager with the command: npm install --save vue-croppa However, when attempting to implement it as usual: import Croppa from 'vue-croppa&a ...

Displaying Product Attribute and Category Names in Woocommerce Title

After reading the answer provided in this thread (Woocommerce: How to show Product Attribute name on title when in a category page and "filtering" products via '?pa_attribute=' on address bar), I am interested in displaying both the categ ...

Develop a diverse range of form types within Django forms

Even though I know how to create a form set based on a given form type, it doesn't completely resolve the issue at hand. Imagine having a fast food portal where users can add items and depending on their selection, additional fields need to be dynami ...

Combining several files into a single variable to encode

I'm encountering an issue with the multiple file upload option. Even though it shows that 2 files have been uploaded, when I try to print the encoded value in the console, it only encodes and takes the value of my last uploaded file. How can I encode ...

Using ContentResult and DataType in an ajax request in Mvc3

Recently, I was on a quest to find a reliable engine for generating charts using Asp.Net Mvc 3. Eventually, my search led me to FusionChart, which offers a wide variety of chart types. In order to assist me in creating the necessary XML to display the cha ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...

Utilizing ajax for fetching a data table

I am new to using ajax and have successfully retrieved data from a table. However, I am now trying to pull in an entire data grid but not sure how to achieve this. In my index.php file, I have the following code: <html> <head><title>Aj ...

Using Vue component with v-model and custom input handler

I'm currently working on creating a wrapper component for an <input/> element in Vue.js. Here is the component code: <template> <div> <input v-bind="$attrs" :value="value" @input="input" /> ... </div> <te ...

Validating JSON in C# using Regular Expressions

In the scenario that I am presented with a JSON string and need to validate it using C#, it is important to understand the structure of a JSON string. The format typically looks like this: string jsonStr = {"Id":123,"Value":"asdf","Time":"adf","isGood":fa ...

How can I retrieve the updated input value once a specific key has been pressed in the prototype?

After a customer presses any key, I would like to check an email. Below is the code I am using: document.observe("dom:loaded", function() { $('billing:email').observe('keypress', function(event){ console.log(event.element(). ...

Issue with implementing autocomplete using AJAX and PHP for multiple input fields

HTML code: <table> <tr> <td align="center"> <label for="InputBox1"><b>~</b><font color="red">*</font>: &nbsp;</label> </td> </tr> <tr> <td align="center"> <div id="1"> ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

What is the best way to merge several fetchMore functions within Apollo?

Can Apollo run multiple fetchMores simultaneously? I have a complex hook that executes two queries and combines their results into a single array. This is how it looks: export const useDashboardState = (collection: string) => { // Getting parameters ...

Angular2 - HTML not displaying the response

I am currently mastering angularjs2. In my latest project, I attempted to fetch data from an API and received a response successfully. However, I encountered an issue where the response is not rendering in homepage.component.html as expected. I am unsure o ...

Adjust color scheme of drop-down menu

Having trouble changing the background color for my drop down menu. I tried to change the color for the sub div but it's not working. Can anyone help me fix this issue? Here is the code snippet: http://jsfiddle.net/3VBQ6/4/ #nav li:hover ul.sub li { ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...