The JavaScript array created from parsing JSON returns a value of undefined

Once again, the gecko scenario! The JSON used in this script to fill a listbox has been validated by JSONLint. The code snippet below demonstrates how the parsed data is placed in arrays:

pdata = jQuery.parseJSON(data);
ctype = pdata[0];
stype = pdata[1];
lizlist = pdata[2];

As the script progresses, I loop through the 'ctype' array (refer to the linked JSON file) using the following code:

lbt = "";
for(var i in ctype) {
lbt += "<option value=\""+ctype[i].id"\"+>"+ctype[i].type+"</option>"
}

However, despite my efforts, the listbox only displays the value "undefined" instead of the expected three options (including one header). To access the problematic javascript file, click here. The webpage where this issue arises is "http://texaslizardconnection.com/#newavailable". Here's some additional information about this javascript:

pdata[0]~pdata[2] should contain arrays.
pdata[2] should contain more arrays.
pdata[0] == pdata["cType"].
pdata[1] == pdata["sType"].
pdata[2] == pdata["lizlist"].

Answer №1

Substitute your loop with:

for (var i=0;i< ctype.length; i++)

You are iterating through each property of the ctype object.

Answer №2

Don't forget to specifically iterate over the cType property when looping through ctype.

Here's the correct way to do it:

for(var i in ctype.cType) {
    lbt += "<option value=\""+ctype.cType[i].id+"\">"+ctype.cType[i].type+"</option>";
}

Answer №3

let parsedData = jQuery.parseJSON(data);
if (!parsedData.cType) {
  alert('Error: cType is null');
} else if (!parsedData.sType) {
  alert('Error: sType is null');
} else {
  // cType is an array!
  let options = "";
  for (let i=0, item; item = parsedData.cType[i]; i++) {
    options += "<option value=\""+item.id+"\">"+item.type+"</option>";
  }
  // continue processing data
}

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

The JQuery datepicker fails to retain the date that is selected

I have a project built with Cakephp 3.6 running locally on my localhost and also deployed on a server. In this project, I am utilizing a datepicker widget as shown below: <?php echo $this->Form->control('created', ['type' ...

Filtering out Objection/Knex query results based on withGraphFetched results

I am working with two models in Objection - "brands" and "offers". Brand: const { Model } = require('objection') class Brand extends Model { static get tableName() { return 'brands' } ...

Retrieving data from the firebase database by filtering based on the child's specific value

Looking at the firebase database, I can see that only the 'name' field is available. Now, I am trying to retrieve the 'quantity' value associated with that specific 'name'. Can someone provide me with a sample firebase query i ...

Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids. I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based ...

Is it acceptable that req.body is void of content? Should we reconsider this approach?

As a beginner in express, I am working on incorporating a basic login feature into my project. However, I am facing some confusion when it comes to passing data around. There are a few aspects that are perplexing me. I currently store the input value i ...

A guide to efficiently managing updates and inserts with bulkCreate in node.js

Currently, I am utilizing node.js to facilitate the uploading of an excel file into a database. Furthermore, in my service, I am employing bulkCreate to efficiently upload the data into the mysql db. In order to provide more context, I will outline the str ...

What are some ways we can enhance Map.get for react-router using ES6 Maps?

I recently implemented a map using new Map() to store my RR4 configuration within my application. My goal is to retrieve the values associated with /countries/:id when accessing /countries/1. routesMap.get('/countries/1') // should provide the ...

What is the process for converting JSON output into a Python data frame?

I have a JSON file that I need to convert into a Python dataframe: print(resp2) { "totalCount": 1, "nextPageKey": null, "result": [ { "metricId": "builtin:tech.generic.cpu.usage", ...

Discovering squares hidden within a group of trees

Imagine being a skilled hunter in a dense forest, surrounded by N tall trees. Your goal is to track down the best deer by constructing fences between the trees to create a perfect square. Imagine having a list of coordinates (x,y) for each of the N trees. ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

Is there a way to retrieve multiple results by utilizing fetch and randomuser.me?

I am currently working with the randomuser.me API and have set up the fetch request correctly. My goal is to retrieve 5 users separated by commas instead of just one. As mentioned in randomuser.me's documentation, I simply need to append the fetch UR ...

Fetching information from a data object using asyncData in Nuxt

Is there a method to retrieve object properties as keys from the asyncData() function? data() { return { bookmark_btn: { status: null, loading: false } } } I attempted to access data object properties in the following ...

The Select2 ajax process runs twice

I am encountering an issue with a script I have that retrieves data from the backend to populate a select2 dropdown. The problem is that the ajax call is being triggered twice every time, which is not the desired behavior. I'm unsure of what mistake I ...

There appears to be a malfunction with WebRupee

I have incorporated the new rupee sign into my website to represent Indian currency. Below is the code snippet I used: For the script, I included " and also added the following: <span class="WebRupee">Rs.</span> 116,754.00 To style it using ...

Error: Unable to load Handlebars helper function

I am working on implementing a custom hbs helper in my Express.js application. However, I keep encountering an error message that says: Missing Helper "if_eq" The code for my page is as follows: <html> <head> <script src="javascript ...

How can ternary conditional operators be transformed into if statements?

When dealing with minified code like this, f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b ...

Swap out the variables in your function with the values selected from the dropdown menu

I've recently started delving into writing JS functions and I'm facing a challenge with the following scenario: On an HTML page, I want to change a variable within a lodash function based on the value of a dropdown and display the result in a HT ...

What is the process of transforming a tree structure into an array?

My tree object is quite irregular with changing children's names and key values each time my code runs. Take a look at an example: { addressRouter: 192.168.0.1, addresses: { address1: 'A', }, ...

Analyzing information extracted from a JSON file that has been converted into a CSV format

I've got a csv file that was generated from a json source. The first column serves as the primary key and contains unique values. Each row after the key column lists attribute codes associated with that key. The number of attributes in each row can va ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...