Troubleshooting: JavaScript Object isn't appending to array

(Just so you know, I really appreciate your help as I navigate through teaching myself).

I'm currently working on recreating an array that was previously parsed from session storage.

var entries = JSON.parse(sessionStorage.getItem('entries'));
console.log(entries);
var stDrivArray = JSON.parse(sessionStorage.getItem('entrynames')); //retrieve from storage
var stDrivArray2 = $.makeArray(stDrivArray); //convert into an array format, but the entries are named as "object". They should be named "Driver"

//here is my attempt to rename them as Drivers
for(var i=0; i<stDrivArray2.length; i++){
    console.log(stDrivArray2[i]);
    var draw2=stDrivArray2[i].draw;
    var name2=stDrivArray2[i].name;
    var name3 = "."+"driver"+stDrivArray2[i].draw;
    Driver[name3] = new Driver(draw2, name2);
    console.log(Driver[name3]);
    DrivArray[DrivArray.length]=Driver[name3];
};
console.log(DrivArray);

An interesting dilemma: When I display Driver[name3] in console, it shows the correct output. For example:

Driver {draw: "5", name: "David Dubczak"}

I am attempting to add each object to the DrivArray, but the result when I print out DrivArray is this:

0: Driver
     draw: undefined
     name: undefined

However, there is indeed one object for each driver within the script! It's just that the values are undefined. It's puzzling because the object is being created correctly, but for some reason the values are not assigned properly to the keys in the array (I hope I'm using the right terminology).

What confuses me more is that I am using the same method to add the same object to the same array on a different page (hence the need to store and retrieve from session storage) and it's working flawlessly.

Any insights on this?

Once again, thank you for your help.

Answer №1

I'm not sure which part you are expecting name3 to have.

Replace:

Driver[name3] = new Driver(draw2, name2);
console.log(Driver[name3]);
//DrivArray.push(Driver[name3]);
DrivArray[DrivArray.length]=Driver[name3]

with:

DrivArray[DrivArray.length]= new Driver(draw2, name2);

Then it should work.

Answer №2

After much deliberation, I arrived at a solution. The Array is now successfully logging to the console.

for(let i=0; i<stDrivArray2.length; i++){
    console.log(stDrivArray2[i]);
    let draw2=stDrivArray2[i].draw;
    let name2=stDrivArray2[i].name;
    let name3 = "."+"driver"+stDrivArray2[i].draw;
    Driver[name3] = new Driver(draw2, name2, 0, 0);
    console.log(Driver[name3]);
    //DrivArray.push(Driver[name3]);
    DrivArray[DrivArray.length]=Driver[name3];
    //DrivArray[] = new Driver(Draw3, name2);
};
console.log(DrivArray);

Moreover, I included two additional attributes to the object, expanding it to:

function Driver(draw, name, points, order) {
    this.draw = draw;
    this.name = name;
    this.points = points;
    this.order = order;

}

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

Utilizing AJAX to dynamically update a div on a separate webpage

In my application, I have a page called news.jsp that displays a list of news titles. Users can click on a title to read the full body of the news, which is loaded using AJAX within a span tag on the same page. Additionally, I display the top 5 news storie ...

Each time the server restarts, Express.js will run a function asynchronously

Looking for guidance on implementing a function in my Express.js app that can fetch data from the database and then cache it into Redis. The goal is to have this function executed only upon restarting the Web server. Any suggestions on how I can achieve t ...

GraphQL is not capable of fetching data directly from a mysql database

Trying to incorporate GraphQL with MySQL in a Node.js Express server has been my recent challenge. Unfortunately, every time I execute my query, an error surfaces. Here is the specific error message: { "errors": [ { "message&quo ...

Consistently directing to a single page on the Node Js web server

I'm in the process of creating a website with multiple HTML pages. Currently, I have code that successfully links to the login page, but unfortunately, the localstores page also directs to the login page. const express = require('express') ...

The issue of "Next.js localStorage not being defined persists, despite attempting to

Despite encountering numerous similar questions, I have not been able to find a solution to my specific issue. This is my first experience utilizing Next.js and TypeScript. I am conducting a mock login with REQRES and storing the token in the localStorage ...

Exploring VueJs 3: Strategies for loading and implementing actions on a component before mounting

Briefly: Can a virtual node be created outside of the DOM to preload images, seek videos... without ever being mounted in the real DOM? Detailed version: I want to ensure that the next slide appears only when it is fully initialized for a slideshow in Vu ...

Creating an onchange event in CodeIgniter for dynamically generated select boxes within a view script

As a beginner with codeigniter, I am seeking some assistance. Within my controller, I retrieve data for both options and suboptions, then load the respective view using the code below. The view essentially generates a table consisting of select boxes passe ...

Maintaining Flexbox layout without triggering item re-rendering for a new container

This is the unique layout I'm aiming to create: I am facing a challenging flexbox layout that needs to be implemented. One of the items in this layout is a Webgl player, which cannot be conditionally rendered due to the restarting issue it may cause. ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

Is it possible to extract information from a string with regular expressions?

As I sift through a myriad of arbitrary "Header" data in node. Here's an example of what it looks like: _Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP= ...

Modify the CSS style of the select label and change the color of the currently selected option in MUI

For the past few days, I've been facing challenges with implementing MUI components while working on a page for a React app. I'm almost finished with my project, but there are 2 key things missing... On my page, I have utilized a Select and an ...

Transferring a uint8clampedarray Array to C# using JavaScript via ajax after extracting getImageData from the Canvas

Currently, I am facing an issue while attempting to create a signature using client-side javaScript and then forwarding the result to the back-end (c#) via ajax. The array I am trying to transmit is of the type uint8clampedarray, but unfortunately, the Set ...

ReactJS safeguarded route redirection/refresh obstacle

Utilizing react and react-router-dom: import React from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; To secure a route with the following: Router const Router = () => { return ( <Switch> ...

I can't seem to figure out why my characters keep disappearing from the HTML string when I attempt to dynamically add HTML using JavaScript

I am currently facing an issue with dynamically adding links to a page. The links are being added successfully, however, the '[' and ']' at the beginning and end of the line are disappearing. Here is the code snippet from my .js file: ...

Breaking up a string using regex with various conditions

(Javascript old version of Node.js) Update: I need to clarify my request. I have a variety of instances like these var name1; CONST name2 Let nam; leT nam VAr n1 ; What I want as output is name1 name2 nam nam n1 Therefore, I am ex ...

FoxyWeb Requests: Utilizing XMLHttpRequest in Firefox Extensions

While I've come across plenty of examples on how to create xhr requests from Firefox Add-ons, I'm currently exploring the new WebExtensions framework (where require and Components are undefined) and facing an issue with sending a simple XmlHttpRe ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

Attributes required are not functional on mobile devices

Good day! I have encountered an issue with the required attribute on a form on my website. It seems to be working perfectly on my browser, but not on mobile devices. Has anyone else experienced difficulties with jQuery, JavaScript, or Node packages? <f ...

The regular expression should consist of just letters and a single dot

Currently, I am working on creating a regular expression that allows only letters and one dot. However, there is a specific rule to follow: the dot cannot be located at the beginning or end of the string. For example: abc.difference This is what I attem ...

Utilize the client's IP address as a cookie in order to recognize return visits and showcase a special message following the initial visit

First of all, a big thank you to anyone who can help resolve this issue. I apologize if this has been asked before (I couldn't find it anywhere, so I decided to post a new question). The main problem I am facing is getting my webpage to show an alert ...