JavaScript's concept of nesting arrays of arrays of objects provides a powerful way

I'm encountering a TypeError saying testsession.testset[0].athletes is undefined. I've tried various approaches but still facing this issue. Is it not feasible to have an array of arrays of objects?

var testsession = {};
var testsetname = {};
var testset = [];
testsession.testsetname = testsetname;
testsession.testsetname = "week9";
testsession.testset = testset;
testsession.testset.push("400M");
testsession.testset.push("800M");

var athletes = [];
var Time = "49.2";
var AthleteID = "a92";
var athlete = { "AthleteID": AthleteID, "Time": Time};
//console.log(pointer);
testsession.testset[0].athletes = athletes;
testsession.testset[0].athletes.push(athlete)
console.log(testsession.testset[0].athletes[0]);

Answer №1

The initial testset[0] value is stored as a string, let's convert it into an object

var testsession = {};
var testsetname = {};
var testset = [];
testsession.testsetname = testsetname;
testsession.testsetname = "week9";
testsession.testset = testset;

//Previously, a direct push of '400m' was causing errors due to being a string
testsession.testset.push({distance: "400M"});
testsession.testset.push({distance: "800M"});

var athletes = [];
var Time = "49.2";
var AthleteID = "a92";
var athlete = { "AthleteID": AthleteID, "Time": Time};
//console.log(pointer);
testsession.testset[0].athletes = athletes;
testsession.testset[0].athletes.push(athlete)
console.log(testsession.testset[0].athletes[0]);

Answer №2

sessionData.sessionArray[0] is a simple value, specifically a string.

This means that the following line of code will not produce the expected outcome:

sessionData.sessionArray[0].players = players;

What occurs in this situation? The primitive on the left doesn't have a players property, so JavaScript transforms it into a String object before adding the property. However, this temporary String object eventually vanishes.

Therefore, it's as if the assignment never happened: sessionData.testset[0] will retain its original primitive value, which does not support additional properties.

If you attempt to access the players property later on, the same process unfolds: JavaScript converts it into a String object and realizes there's no players property available, resulting in the return of undefined.

Answer №3

If you attempt to retrieve the value of testsession.testset[0], it will be returned as a string. To ensure correct functionality, consider initializing testsession.testset[0] = {}; before attempting to access any of its properties.

Answer №4

It seems like you've got the code working just fine!

<script >

var testsession = {};
testsession.testset = [];
testsession.testset.push({testsetname:"week9"});
testsession.testset[0].list = [];

testsession.testset[0].list.push({distance:"400M"});
testsession.testset[0].list[0].athletes = [];
testsession.testset[0].list[0].athletes.push({ AthleteID:  "a92", Time: "49.2"});

testsession.testset[0].list.push({distance:"900M"});
testsession.testset[0].list[1].athletes = [];
testsession.testset[0].list[1].athletes.push({ AthleteID:  "a93", Time: "99.2"});

console.log(testsession);

</script>

Here's the expected output:

"{"testset":[{"testsetname":"week9","list":[{"distance":"400M","athletes":[{"AthleteID":"a92","Time":"49.2"}]},{"distance":"900M","athletes":[{"AthleteID":"a93","Time":"99.2"}]}]}]}"

https://i.sstatic.net/ImmLn.png

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

Why does NPM keep flagging dependencies as unmet even though they are clearly installed and met?

Currently, I am in the process of setting up angular2 with typescript and node. However, I keep receiving warnings about unmet peer dependencies even though they seem to be available: tyler@tyler-Blade-Stealth:~/projects/mockups$ npm install -g @angular/c ...

Display a notification badge using Firestore

Hey there! I am currently developing a chat application using Firestore. While researching, I found plenty of information on creating badge notifications with cloud messaging, but not much without it. Can anyone help me out with this? I want to display a n ...

Issues with jQuery custom accordion functionality in Internet Explorer, Safari, and Chrome browsers

When a corresponding <a> is clicked, my script should expand/collapse UL elements. It works perfectly in Firefox and you can check it out here. First, I load the jQuery library and then my own examples.js file which includes: function initExamples( ...

Using Rails 5 and Ajax: Comments will only be appended if a comment already exists

I have been working on a new feature that allows users to add comments to articles using Ajax. However, I have encountered an issue where the comment only gets rendered successfully through Ajax if there is already one existing comment. The database commit ...

Executing a series of tests using Postman

Is running multiple requests in a postman script feasible? I have an endpoint: http://localhost/gadgets/{id}/buy This endpoint sets a flag in a gadget object/entry based on its id. With hundreds of gadgets, can I use a shared file of ids to create and run ...

Retrieving Form Values from Child Components in React upon Submission

Query: I am facing an issue with my SignForm component where I am unable to pass the input values from SignForm to the parent Component, even though I have tried various solutions found online. I have a parent component called Login which calls the SignFo ...

Getting response header data in Next.js is a piece of cake!

In my nextjs application, I am trying to access the response headers of an HTTP request. While I can view all the response headers in the browser's devtools under the network section, I am unable to fetch them within the actual code. The only headers ...

I am experiencing an issue where the submit button in my HTML form is unresponsive to clicks

Welcome to my HTML world! <form action="petDetails.php" id="animalInput"> <ul> <li> <label for="dogName">Enter Dog's Name:</label><input id="dogName" type="text" name="dogName" /> </l ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

Advantages of using individual CSS files for components in React.js

As someone diving into the world of Web Development, I am currently honing my skills in React.js. I have grasped the concept of creating Components in React and applying styles to them. I'm curious, would separating CSS files for each React Component ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

I require assistance in computing the total number of subordinate tags present within KML files

I have a task to convert kml files and insert them into a MySQL database. However, I am facing some confusion in counting the number of child tags with the name "folder" under my kml files. Here are two examples of kml files: Example 1: <?xml version= ...

use a jQuery function to submit a form

I have an HTML page with a form, and I want to display a specific div when the form is successfully submitted. The div code is as follows: <div class="response" style="display: none;"> <p>You can download it <a href="{{ link }}">here&l ...

Is AngularJS really as safe as they claim?

Just seeking confirmation. Consider this AngularJs code: $rootScope.myNeededBoolean = false; $rootScope.$on('userHasJustBeenAuthenticated', function(){ if(!$rootScope.myNeededBoolean) { $rootScope.myNeededBoolean = true; ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Unset a random element within a multidimensional array if a specific key-value pair is present

Currently, I am working with a multidimensional array in PHP that is structured as follows: $data = array( array('spot'=>1,'name'=>'item_1'), array('spot'=>2,'name'=> ...

Ensuring an element matches the height of its child using CSS styling

How can I ensure that the parent element's height adjusts to match the height of its child element using CSS? <div class = "parent"> <div class="child"> </div> </div> ...

Create an array of references

A task I need to complete involves performing a series of steps on an array: First, create an array of references outside the component Next, build a form Within the form, map through the array and render an input for each element When an input is in focu ...

Using PHP, jQuery, and HTML to submit a form and insert data into MySQL, all while

I am facing an issue with my PHP intranet site, which includes an HTML form with 2 input fields. My goal is to take the user's input from the form and insert it into a MySQL database without redirecting the user to another page. I have a separate PHP ...

Retrieve the user-inputted data from an Electron BrowserView's input field

Consider this scenario where a BrowserWindow is set up with specific security settings, including enabling the webviewTag: true for project requirements. let webPrefs = { plugins: false, nodeIntegration: false, nodeIntegrationInWorker: false, ...