When using a variable to fetch data in JSON, an undefined error occurs. However, if a hardcoded index

I am facing an issue while trying to extract and manipulate JSON data from a file for an application I am developing. When looping through the data, I encounter an undefined error that seems to indicate a missing property in the JSON object when accessing it with a loop variable. However, if I directly index the JSON array with a hardcoded number, the property loads correctly. I need assistance in resolving this issue. Below is a snippet of the code along with the JSON data:

I have attempted various methods like stringifying and parsing the JSON data again, as well as trying both square brackets and dot notation for access, but all lead to the same problem.

Code snippet to access the JSON data:

import ontology from '../../data/ontology.json'

const totalAnswerList = ontology.answers

for (var i = 0; i <= totalAnswerList.length; i++) {
            var wordID = totalAnswerList[i] // wordID.id returns undefined
            var wordID2 = totalAnswerList[0] // wordID2.id works
            alert(JSON.stringify(wordID) + JSON.stringify(wordID2) + '\nWord ID hardcoded: ' + wordID2.id)
}
//ontology.json
{
    "answers": [
        {
            "id": "examination",
            "category_id": "examination",
            "synonyms": ["examination"]
        }, ...
    ], ...
}

Answer №1

Your provided code is functioning as intended, however, the problem lies in the final element being undefined due to the constraints of your for loop. It would be more appropriate to use i < totalAnswerList.length instead of <=. This way, if the array consists of 5 elements, you will iterate through 0, 1, 2, 3, 4 (and not 5, which results in undefined).

import ontology from "./ontology.json";

const totalAnswerList = ontology.answers;

for (var i = 0; i < totalAnswerList.length; i++) {
  // ...
}

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

Having issues setting a property value on a Mongoose result in a Node.js application

Hello there, I am currently working with a MongoDB object retrieved via a findById method, and I need to convert the _id within this object from an ObjectID type to a string. I have developed the following function: student: async (parent, { _id }, ...

Struggling to determine the expense upon button activation - data remains stagnant

My coding project involves a basic ordering system where users can input an integer, click on an update button, and see the total cost displayed below. Despite my efforts, I've encountered issues with two different methods: Using plain JavaScript for ...

Encountering an NPM ELIFECYCLE error when attempting to start the node server with the

After following the instructions on deploying test-bot on IBM Watson from this link https://github.com/eciggaar/text-bot, I encountered errors while attempting to deploy the code locally using CLI foundry. My setup includes Node.js version 6.10.3 and npm ...

reinitializing an array duplicate within an angular function following the use of .splice()

My goal is to create a dropdown menu in Angular that automatically removes the current page from the list when navigating to another view. I want the menu to reset and remove the now-current view every time a new view is loaded. This is the array of objec ...

Using JavaScript closures together with a timeout in the onKeyUp event

My goal is to add an onKeyUp event to all input fields within a form using closures. The array fields holds the names of the fields that need this event, while the array ajaxFields contains the names of fields requiring ajax validation. function createEve ...

Ways to send a JSON object to a Node.js server

I am working on developing a hybrid mobile application with Node.js as the backend and MongoDB for saving data. My server is functioning properly, and I have set up routes to handle user requests. While I can retrieve data from my server using the GET met ...

Create a JSON object that organizes a collection with indexed items

Is there a library available that can generate a JSON object where a collection is represented as a set of numbered items? For example, when using the GSON library with a class like this: `class Bus { List<Passenger> passengers; ...

Having difficulty in choosing and displaying the dropdown values

Below is the code snippet: WebElement pooldropdown=driver.findElement(By.xpath("/html/body/section/section[2]/div[1]/select")); Select sel = new Select(pooldropdown); List<WebElement> list = sel.getOptions(); System. ...

Guide to extracting and utilizing a JSON object received from the parent page

Hello, I've been searching online for quite some time and can't seem to find a solution to my question. If anyone could help, I would greatly appreciate it. Below is the code I am working with: <ion-content> ...

Creating snake_case format for definitions in swagger.json within Dropwizard

I am currently working with the dropwizard framework on a project where I have implemented the @JsonSnakeCase annotation to convert CamelCase format to snake_case. However, when I attempt to generate swagger.json using swagger annotations, the definitions ...

Javascript callback function cannot access variables from its parent function

As a Javascript newbie, I am currently diving into callbacks for my project. The goal is to retrieve address input from multiple text boxes on the HTML side and then execute core functionalities upon button click. There are N text boxes, each containing an ...

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

Show nested arrays in Vue.js exhibition

As a newcomer to vue, I've been navigating my way around with some success. Lately, I've been dealing with JSON data structured like this: [ { "name": "jack", "age": "twenty", "Colors&qu ...

I'm running into an issue with deserialization and getting an error from Newtonsoft.Json.JsonConvert. Can anyone

public List<CoinMarket> GetCoinMarket() { List<CoinMarket> coinMarket = new List<CoinMarket>(); var URLWebAPI = "http://190.202.54.19/wsZeus/api/Account/Markets/Get"; try { using (var Client = new System.Net.Http.H ...

Differentiating Between Arrays and Objects in AngularJS ng-repeat

When using ng-repeat to display data in a View from an endpoint in the form of an atom feed, I encountered an issue. The endpoint returns JSON if the Accept header is 'application/json', but when there is only one entry in the atom response, the ...

Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox? I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated. Here is the solution I came up wi ...

Is it feasible to set a default value in an HTML input field that is not editable using JavaScript?

Is there a way to set a default value in an input field of HTML that is not editable, and then allow users to add additional text to it? For example, having 'AB' as the default and uneditable starting characters, followed by any numbers such as A ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

Transferring mouse events from iframes to the parent document

Currently, I have a situation where my iframe is positioned over the entire HTML document. However, I am in need of finding a way to pass clicks and hover events from the iframe back to the main hosting document. Are there any potential solutions or alter ...

Implementing type-based validations in Vue.js 3 using Yup

Greetings! I am facing a minor issue that needs to be addressed. The scenario is as follows: I need to implement validation based on the type of member. If the member type is corporate, then the tax number should be mandatory while the phone number can be ...