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

Tips for correcting the `/Date(xxxxxxxxxxxxx)/` formatting issue in asp.net mvc

As a programming novice, I am trying to display data from my database server on the web using a datatable in asp.net mvc. After following a tutorial video on YouTube, I encountered an issue where the date and time columns in my table are displaying as /Dat ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

Delay the next loop iteration until receiving an HTTP request

I have a task where I am collecting YouTube video IDs and storing them in an array. Then, I am looping through each video ID to determine the size of that ID's thumbnail image. My challenge now is making sure my loop waits for the HTTP request to fini ...

Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play ...

Is there a way to export a variable that has been declared within a function component in React Js?

I am currently developing a React app and I need to export the RoomPricelist1 & FacilityPricelist1 variables. I have assigned values to these variables within a function component but when I try to import them into another function component, they are sh ...

Tips for steering clear of getting caught in the initial focus trap

I have implemented Focus-trap (https://www.npmjs.com/package/focus-trap) in my modal to enhance keyboard accessibility. Here is a snippet of my code: <FocusTrap focusTrapOptions={{onDeactivate: onClose}} > <div> ... </div> <Focu ...

JS Issue with Countdown functionality in Internet Explorer and Safari

I am having an issue with a JavaScript countdown not working on Internet Explorer and Safari, despite being tested on Windows 7. It works fine on Chrome and Firefox. I am unable to switch to a jQuery countdown due to certain restrictions on the website, so ...

Tips for retrieving Angular JSON data

Can someone assist me with extracting separate values from the JSON returned by an API? { ACC: "{"NO":"AC307","NAME":"joe"}, RETURN: "TRUE" } I need to retrieve the values individually, such as NO and NAME. How can I achieve this? Below is a snippet of ...

Scrolling to the active list item in the navigation bar

Having an unordered list with the id mainul in the navigation bar is causing a problem when the page reloads. The navigation bar always starts at the beginning, but I would like it to automatically scroll to the active li element. This is my HTML code: & ...

Issue with Click event not working on dynamically added button in Angular 8

My goal is to dynamically add and remove product images when a user clicks the add or delete button on the screen. However, I am encountering an issue where the function is not being called when dynamically injecting HTML and binding the click event. Below ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

Issue encountered when attempting to set a default value in Material-UI Text Field while interacting with Redux state?

Struggling to assign a defaultValue property for a Text Field using data from Redux state, but the updates are not reflecting as expected. The value is passed down as a prop from the container component to the edit component like this: render() { const ...

npm package.json scripts not executing

Whenever I try to run npm start or npm run customScriptCommand, npm seems to not be executing anything on my project and just quickly returns a new line in the terminal. I attempted to solve this issue by uninstalling node and npm from my machine, then in ...

Can data be transferred from one website to another without the use of an API?

I am a newcomer to the world of web development with basic knowledge of JS, Node, Express, Mongoose, and MongoDB. I have an exciting idea for a web application that would function like a spreadsheet, gathering user inputs to generate an output. The unique ...

Incorporate ng-model to manage dynamically generated HTML elements

I have created dynamic div elements with a button inside, and I want to access its value using ng-model, but the value is not being retrieved. Here is my code: var url = "/api/chatBot/chatBot"; $http.post(url,data) .success(function(data){ $scope.mes ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Having Issues with Loading More Button Functionality in Selenium Automation

Here is a snippet of my code. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected ...

Unable to Retrieve JSON Output

PHP Code: $contents = ''; $dataarray = file('/location/'.$_GET['playlist'].''); //Loading file data into array $finallist = ''; //Extract Track Info foreach ($dataarray as $line_num => $line) //Loopin ...

Tips for including an additional class in an element

I have an image tag with the "kiwi" class, and another class that makes it spin. I want to toggle this second class (called 'elem') when clicking on the play button of my music player. Here is the image tag with the class: <img src="./im ...

Turn off the use of to_json and from_json functions when the data types of member variables do not align with nlohmann's json library

Utilizing nlohmann's single header json library to serialize a custom class is proving to be challenging. The goal is to make this class compatible with various types, including boost's multiprecision types. However, certain types, like boost&apo ...