unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded:

[Object, Object, Object, Object, Object, Object, Object, Object, Object]

0: Object
depTime: "2014-12-04 18:35"
destination: "Norsesund station"
nr: "562"
operator: "Västtrafik"
typText: "Buss"
__proto__: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
length: 9
__proto__: Array[0]

I attempted to do the following...

for (var i = 0; i <= pResult.length; i++) {
    var html =  html + '<tr>';
    var html =  html + '<td>';
    var html =  html + pResult[i].depTime;
    var html =  html + '</td>';
    var html =  html + '</tr>';
}

... but encountered this error message:

Uncaught TypeError: Cannot read property 'depTime' of undefined

Answer №1

Revise :

i <= pResult.length;

To:

i < pResult.length;

Since arrays are 0-based indexed, with a length of 3 you only have indexes 0, 1, and 2 available.

Answer №2

To avoid using a loop, you have the option to utilize the reduce method:

var html = pResult.reduce(function(previousValue, currentValue) {
    return previousValue + '<tr><td>' + currentValue.depTime + '</td></tr>';
}, '');

Keep in mind that this method is supported in all modern browsers except IE 9+ (you can use a polyfill if necessary for older IE versions).

Answer №3

Give this a shot:

for (let i = 0; i < pResult.length; i++) {
        let html =   '<tr>';
            html +=  '<td>';
                html +=  pResult[i].depTime;
            html +=  '</td>';
        html +=  '</tr>';
}

The issue is that you are looping until the length of the array, but arrays start at index 0 so
if you have an array like this

var pResult= [object1, object2, object3];

pResult.length =3
pResult[3] does not exist and is undefined.
NOTE: Instead of recreating the variable when adding text, just append it to the existing one. For example, use html+="the added text"

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

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

Executing asynchronous functions synchronously

I am relatively new to JavaScript programming and I am currently trying to grasp the concepts of asynchronous processes. In my project, I am looking to execute the following code synchronously. Despite watching numerous tutorials on the subject, I find mos ...

Vanishing HTML upon initial entry to the site using Gatsby and Material UI exclusively in live deployment

I run a blog using Gatsby that includes Material UI components to fetch markdown files through GraphQL. During development, everything operates smoothly. However, in production (after running gatsby build && gatsby serve), the HTML doesn't di ...

Error code 403 has been reported by Stripe's payment_init.php as a forbidden request

Having some trouble incorporating a Stripe payment method into my web application. I've hit a roadblock: payment_init.php isn't loading when I'm redirected to the page. Instead, I'm greeted with a 403 Forbidden error code ("Forbidden. Y ...

NextJs redirection techniquesWould you like to learn the best ways

Currently, I am developing an application using NextJS with Firebase authentication integration. Upon successful authentication, my goal is to retrieve additional customer details stored in a MongoDB database or create a new document for the customer upon ...

Converting Nested Classes into Rows in a Table using Spring Framework

Currently, I am utilizing Spring Boot along with several essential dependencies such as Jackson and Hibernate. Within my project, there exists a table named Buildings which consists of columns like Unit, Number, Street, and more. However, instead of direct ...

Retrieve an array from JSON encoding using AJAX

I have been attempting to retrieve 4 JSON arrays stored in a separate file and include them in my main file using an AJAX request. However, I'm facing difficulties storing these arrays into variables and logging them in the console. Here are the resul ...

Having trouble with MUI auto import suggestions in my Next.js 13 project on VS Code

I'm currently developing a project using Next.js 13 and have installed MUI. However, I am encountering an issue where VS Code is not providing auto imports from the @mui/material library, as shown in the attached screenshot. https://i.stack.imgur.com ...

Utilizing a combination of ORMLite, JSON, and foreign objects revolution

Consider a scenario where we have a basic ORMLite data model (with annotations) in an Android App: A { String id; } B { String id; A A_id; } If we are receiving objects from a PostgreSQL external database where A_id is stored as a String, how ...

Merging nested JSON arrays with column groups in Snowflake

I am currently utilizing Snowflake for JSON parsing and have a query that produces a concatenated string for Resource and Action keys within the Statement array. Within GROUP and ROLE, there are multiple lists of Statements, and my goal is to create a sing ...

Extracting data from a Wikipedia table using web scraping in JavaScript

I'm attempting to extract information from a specific website. <script> var convertToInt; var allData = []; $.ajax({ url: "http://en.wikipedia.org/wiki/Demographics_of_Europe", type: 'GET', cache: false, success: func ...

Troubleshooting Vue.js data binding problems

Utilizing HTML targeting with data binding <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div class="row" v-for="test in tests"> <div class="col-12"> <router-link tag="a" :to="{ name: ...

The browser message states: Variable $? Not Found

As a newcomer to javascript (jquery/json), I've created code to display a chart using CanvasJS with a php/json data fetching script. However, I'm facing an issue where the chart is not rendering when I integrate my code. Upon inspecting the brows ...

Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the c ...

Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert. There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id. Vue.component('query-status ...

Animated CSS Checkmark Design

How can I create an animated Check-mark using CSS with SVG animation? I attempted the following code but it doesn't seem to be working. Any suggestions? DEMO: https://jsfiddle.net/b7Ln0jns/ CSS: @import "bourbon"; $color--green: #7ac142; $curve: c ...

Using raphaeljs and freetransform in conjunction with clip-path

Currently, I am utilizing Raphael along with Elberts FreeTransform Plugin. You can view my progress so far by visiting MyWork The issue arises when I attempt to translate or rotate the set of rectangles within my clip path. Once rotated or translated, it ...

Having trouble with $addToSet and $push not working in updates using Mongoose with MongoDB in Node.js?

My issue involves Mongoose as I am attempting to update a document in MongoDB using the mongoose module. Below is my schema: var User = new mongoose.Schema({ name: String, email: String, list_houses: [{ id_house: S ...

Transforming JSON data into string format

Looking for a way to convert the JSON below into a fully string-quoted JSON format using Python. Is there a method in the python "json" module that can help with this, or is there a simpler parsing code available? Original data: data = '[{"id":334," ...