Generate a new JavaScript object and populate it with information

I am looking to create a JavaScript object in the following format:

var CarList = {};

I then want to populate it using a for loop (retrieving data from a MySQL database) similar to this:

for(var i = 0; i < result.length; i++)
{
     CarList.Constructeur = result[i].Constructeur;
     CarList.Modele = result[i].Modele;
     CarList.Couleur = result[i].Couleur;
     CarList.Immat = result[i].Immat;
     CarList.VIN = result[i].VIN;
     CarList.DMC = result[i].Date_Mise_en_circulation;
     CarList.Enregistrement = result[i].Date_enregistrement;
}

The issue I am facing is that only the last car in the database is being displayed. I believe I am missing an [i] somewhere in my code, as it is only creating one car child instead of multiple as per my database.

What is the correct way to address this issue?

I have already attempted using CarList[i], CarList.[i].*, and CarList.car[i].*

Answer №1

If you're looking to convert CarList into an array, be sure to initialize it using square brackets instead of curly brackets. Additionally, make sure to create a new object for each element in the array.

let CarList = [];

for(let i = 0; i < result.length; i++)
{
    // Create a new object
    CarList[i] = {};
    CarList[i].Manufacturer = result[i].Manufacturer;
    CarList[i].Model = result[i].Model;
    CarList[i].Color = result[i].Color;
    CarList[i].PlateNumber = result[i].PlateNumber;
    CarList[i].VIN = result[i].VIN;
    CarList[i].DMC = result[i].Date_of_Manufacture;
    CarList[i].Registration = result[i].Registration_Date;
}

Answer №2

In my opinion, organizing an array of car objects would be beneficial. One way to accomplish this is by utilizing a map function as shown below:

let carList = result.map(car => {
 return {
        Make: car.Make,
        Model: car.Model,
        Color: car.Color,
        LicensePlate: car.LicensePlate,
        VIN: car.VIN,
        DMC: car.Date_Mise_en_circulation,
        Registration: car.Date_enregistrement
     }
})

Another approach is to stick to your current coding style and make use of arr.push()

let carList = [];
for(var i = 0; i < result.length; i++)
{
carList.push({
  Make: result[i].Make,
  Model: result[i].Model,
  Color: result[i].Color,
  LicensePlate: result[i].LicensePlate,
  VIN: result[i].VIN,
  DMC: result[i].Date_Mise_en_circulation,
  Registration: result[i].Date_enregistrement
 })
}

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

When incorporating Vue as an npm package, a Vue 3 app may inadvertently clear the mounted element upon initialization

I have a straightforward Vue 3 application that is working perfectly fine when I include Vue as a script, as shown in the code snippet below. However, I need to integrate it with webpack by including it as an npm package. When I do this, the app loads but ...

Manipulate HTML elements using JavaScript when a key is being held down

I'm currently developing a simple game using vueJS for the frontend. I have successfully created all the necessary objects and now my goal is to enable their movement when a key is pressed. However, I am facing an issue where the object only moves on ...

Is there a way to display a message box when the mouse cursor hovers over a text box?

Currently, I have set up 3 text boxes in my project. The functionality I am trying to achieve is when the user clicks on the second text box, the value of the first text box should be displayed in a message box (providing that the validation for the first ...

Having difficulty implementing the .fadeIn jQuery function on a script for transitioning homepage images

I'm a beginner and I'm not sure if fadeIn is the right transition, but I want to create a crossfade effect between homepage images that switch every 3 seconds. The image changing is successful, but I can't figure out how to make them fade. C ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

How come all the toggle switches are operating simultaneously?

** I have encountered an issue with storing toggle switch values in local storage. When I try to turn one toggle switch "ON", all the toggle switches turn "ON" simultaneously. This problem arises after using checked={value} in the tag. Can someone ple ...

I am encountering an Uncaught TypeError while diagnosing the issue: why is __webpack_require__(...).createServer not functioning as expected

I am currently working on a Vue project that integrates with Stripe. However, I encountered an error when I loaded my workspace recently, and I am having trouble figuring out how to resolve it. Oddly enough, the live version of my project is functioning p ...

Creating personalized Date and Time formatting on the X axis in Lightningchart JS

I have an X-axis representing time intervals in 15-second increments. ["2020-05-22 14:20:22", "173.9"] ["2020-05-22 14:20:40", "175.3"] ["2020-05-22 14:20:58", "172.4"] In my attempt to add this data to the chart, I used the following code: for(var key ...

Using both ng-if and ng-click in AngularJS for enhanced functionalities

There's a button that should display a toggle only when the value is greater than 0; otherwise, it shouldn't do anything. This snippet of code shows how things were prior to adding ng-if: <span >{{values.valuesNumber}} <i class= ...

Is there a way to refresh the animation on dougtesting.net?

I'm working with the dougtesting.net library to create a spinning wheel. I've been trying to figure out how to reset the animation once it finishes, but I can't seem to find any information on it. My goal is to completely clear all states so ...

The property 'createUploadWidget' cannot be read from an undefined source

While working on a React js tutorial, I encountered an issue related to using Cloudinary React SDK for image and video uploads. Specifically, I was using the Upload Widget provided by Cloudinary and faced an error when trying to open the widget - 'Typ ...

Operating two independent Angular applications simultaneously on a single webpage

I'm currently developing an application that allows multiple Angular applications to be embedded within a main frame. Currently, I am using IFrames for this purpose, which is functioning well but has its limitations. I am exploring ways to embed ano ...

The problem arises when trying to use the Jquery click event on buttons that have been generated

I've encountered an issue where I can create components dynamically, but the click event doesn't seem to work on buttons that are dynamically generated. Check out the code snippet below: HTML file: <div class="merge_sections">&l ...

"At the beginning of an array in JavaScript, I often encounter the issue of receiving

Here is some code that I created: function get_coordinates(container) { var x; var y; var divs = container.getElementsByTagName('div'); Array.from(divs).forEach(div => { y += div.offsetTop+" "; x += d ...

Effective methods to avoid showcasing AdSense advertisements

For the purpose of creating a responsive design, I am attempting to hide an adsense ad unit on smaller screen sizes. Although I am familiar with the method of using css media queries as outlined on Google AdSense support page, I have encountered an error w ...

Create a compressed package of a Vue project that can easily be inserted into a Blogger blog post as a single HTML file

Is there a way to package all the files related to a Vue.js project (HTML, JavaScript, CSS) into one single HTML file for easy deployment on a Blogger Blogspot post? In the past, a question similar to this was asked regarding bundling files into a single ...

Looking for guidance and bug assistance in HTML and JS, possibly involving PHP and MySQL. Can anyone offer advice?

I'm attempting to create an auto-complete feature for a forum (similar to the tags below) that will function within LimeSurvey. I am fairly new to this, so please provide explanations as if you were explaining it to a 5-year-old :) My objectives are: ...

Using axios to retrieve data and then sending it to a localhost server using express

I'm a beginner in javascript and currently experimenting with fetching data from an API and posting it to my own server (localhost). For fetching the data, I am using axios as shown below: async function getNCAA() { axios .get(`https://api.th ...

The occurrence of the error "Failed to resolve component" in Vue 3.0.11 seems to be random, particularly when using recursive components

After thoroughly checking all similar questions on this platform, I did not find any relevant solutions. In most cases, the error seems to occur when utilizing components:[comp1,comp2] This is incorrect because the components property should be an object. ...

Leveraging JSON data to dynamically create HTML elements with multiple class names and unique IDs, all achieved without relying on

Recently, I've been working on creating a virtual Rubik's cube using only JS and CSS on CodePen. Despite my limited experience of coding for less than 3 months, with just under a month focusing on JS, I have managed to develop two versions so far ...