Outside of the for loop, a JavaScript object is accessible, but inside the loop, it is undefined

I have a question that I need help with. After parsing a JSON object from an AJAX request, I obtained an object called usrobj.

console.log(usrobj.available[0]);

The usrobj.available is actually an array:

(2) [{…}, {…}]
0:{currency: "ETH", amount: "0.5"}
1:{currency: "BTC", amount: null}
length:2
__proto__:Array(0)

This resulted in a vardump like this:

{currency: "ETH", amount: "0.5"}
amount:"0.5"
currency:"ETH"
__proto__:Object

However, when I tried to loop through the array using the following code:

for(i = 0; i < usrobj.available.length; ++i) {
    $('#assets-table').append('<tr>\
      <td>'+usrobj.available[i].currency+'</td>\
      <td>Available: '+usrobj.available[i].amount+' (Frozen: '+usrobj.frozen[i].amount+')<br /></td>\
...removed for brevity...

I encountered an error message: Uncaught TypeError: Cannot read property '0' of undefined

at Object.success (readAssets.js:22)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)

If anyone could advise me on whether they are in different scopes and how to fix this issue, I would greatly appreciate it.

Answer №1

The "frozen" property is missing from your object

Therefore, when trying to access "usrobj.frozen[i].amount", it results in a crash

If the value of usrobj.frozen at a certain index matches that of usrobj.available, you will need to implement something like this:

let usrobj = {
  available: [
    {currency: "ETH", amount: "0.5"},
    {currency: "BTC", amount: null},
  ],
  frozen: [
    null,
    {ammount: '10'}
  ]
}

for(let i in usrobj.available){
  console.log(
    `Avaiable ${usrobj.available[i].amount}
    Frozen ${(usrobj.frozen && usrobj.frozen[0] && usrobj.frozen[0].amount) || 0}
    `)
}

Answer №2

While executing the code usrobj.available[i].currency within the jQuery append function, consider storing the this reference in a variable outside the jQuery function and then accessing usrobj.available[i].currency inside the append function using ref.usrobj.available[i].currency

for(i = 0; i < usrobj.available.length; ++i) {
    let ref = this;
    $('#assets-table').append('<tr>\
      <td>'+ref.usrobj.available[i].currency+'</td>')
 ....     
}      
This is a brief snippet to demonstrate the concept

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

Is it possible to create a jQuery animation that toggles from top to bottom with a 'slow' speed setting?

I recently implemented a hidden div appearing/disappearing animation in my code using jQuery's toggle('slow'). The current effect makes the div expand from the upper left corner to the bottom right corner. Is there a way to modify the anima ...

Passing a JavaScript variable through a URL link

I need to pass a JavaScript variable to a specific webpage. Here is the code I am using: <script> function hello() { var data="hello"; <a href="www.mytestsite.com?var="' +data +'>Send now</a> } </script> The hello() func ...

issue with nodeJS spawn child_process on glitch.com

I am attempting to set up an express server on glitch.com using the code provided below: const path = require('path'); const { spawn } = require('child_process'); const express = require('express'); const app = express(); app ...

Utilize AdWords Scripts/Javascript to display array objects on separate rows within a spreadsheet

I am currently facing some difficulties in figuring out how to display objects from an Array on separate rows within a spreadsheet using Google AdWords. var SPREADSHEET_URL = "xxxx"; function main(){ var spreadsheet = SpreadsheetApp.openByUrl(SPREADSH ...

Having trouble with updating a Firebase database object using snap.val()

I'm trying to figure out how to update a property within the snap.val() in order to make changes to my Firebase database. function updateListItem(listItem) { var dbRef = firebase.database() .ref() .child('userdb') .child($sco ...

I'm experiencing difficulties inserting data into my RECHARTS chart

I have several sets of data arrays from an API that I receive, and I need to use the [1] index of each array on the line and the [0] index on the axis of my chart. DATA SET 31) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2 ...

Query the total quantity of items within the JSON data on an iOS platform

Hey there, I've successfully created a JSON request using the code snippet below: for (int i=0; i<= [urls count]-1; i++) { self.items=[[NSMutableDictionary alloc] init]; [self.items setObject:[names objectAtIndex:i] forKey:@"results"]; ...

Is it possible to obtain the className of a leaflet divIcon within the <style scoped> portion of a vue component?

If you're looking for a Vue 2 sample project, check out this link When working on the declaration of divIcon in LeafletTest.vue, here is an example: const cloudIcon = L.divIcon({ html: thecloud, className: 'my-custom-icons& ...

Trying out a function named on Sinon.js spy

Currently, I am utilizing SinonJS to verify that my controller is calling certain methods within my view. Specifically, I am aiming to confirm that the addSeat method is invoked with the value of testSeat. Despite my efforts in the code snippet below, I am ...

Tips for designing a three-dimensional egg shape using Three.js?

I'm looking to create a unique egg shape using Three.js, but I seem to be missing the correct equation. Below is the code I currently have, utilizing LatheGeometry. Can anyone provide some guidance? var r0 = 40 var r1 = r0/4; var inc = Math.PI/r0; po ...

Retrieving information from a PHP server using AJAX

Searching for a way to retrieve the posts created by users and load more posts upon user's request. Encountering an Unexpected end of JSON input error when initiating an ajax request in the console. Javascript $("#ajax_load_more").click(function ...

Struggling to create a foreach loop for a multi-dimensional array containing StdClass Objects

Currently, I am diving into PHP and CodeIgniter with little experience in modern programming. Thus, I would appreciate any kind guidance you could offer! I recently crafted a function to compute weekly totals of kilometers cycled on a bike from a MySQL ta ...

Clicking on an `Option` in the `Select` triggering an `Ajax function` works properly in Firefox, however it is not functioning as expected in Chrome

When using the onClick Event in the Option tag, it performs properly in Firefox and triggers the myPurchaseTotal function as expected with Ajax working perfectly. However, in Chrome, this functionality does not work. Below is the code snippet for reference ...

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

When a node sends a request to an endpoint, it receives a response from

In my project, I have a file named "forms.routes.js" which contains a variety of endpoints using router.get, router.post, router.put, and router.delete. Interestingly, when I try to access the 16th endpoint in the list: localhost:3000/v2/forms/:domain/co ...

Developing shell scripts and utilizing jQuery

I want to execute a linux command that returns the currently logged on user in linux. Using jQuery and ajax, passing this command to the PHP, which will receive and execute this command using exec() function. The value should be stored and returned. Upon ...

Utilizing JSON.parse to interpret the incoming request

When attempting to parse a request using node.js, the following code is utilized: app.get('/download', function(req, res){ var parseJson = JSON.parse(req); var file = parseJson.fileName; res.download(file); // Set disposition ...

Measuring the number of distinct words within a given set of strings

Describing my attempt to create a function that processes string arrays by adding unique words to a word array, and incrementing the count of existing words in the count array: var words = []; var counts = []; calculate([a, b]); calculate([a, c]); funct ...

The element's location within the array exceeds capacity, leading to an overflow issue

Concern with the item's address in array increasing to a point of overflow struct payment { char id[17]; char date[10]; int cost; struct payment* next = NULL; }; int main() { payment* data = (payment*) malloc(n * sizeof(payment)) ...

What is the best way to create a table of buttons with seamless integration, leaving no gaps between each button?

While developing a website, I encountered an issue where I couldn't figure out how to eliminate gaps between buttons. Despite searching online for a solution, I struggled to articulate my problem clearly. Essentially, I am trying to create a table lay ...