Search code examples
javascriptobjectjavascript-objects

Create a javascript object and fill data in it


I want to create a Javascript object like this :

var CarList = {};

then fill it with a for loop (data is taken from a MySql database) like 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 thing is that only the last car of the database is showing . i'm missing a [i] somewhere. it only create one car child and not as many as my database.

How can i fixe it .

I already tried CarList[i] , Carlist.[i].* and , Carlist.car[i].*


Solution

  • If you want CarList to be an array, initialize it with square brackets, not curly brackets. You will also need to create a new object at each spot in that array.

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