0

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].*

1
  • You are overwriting the value on each assignment. Commented Oct 13, 2017 at 12:03

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This way is working fine . but now i have an array of object . how can i send this array into a EJS template (sorry if it's too much out of scope)
The front page of www.embeddedjs.com has an example using an array. Is that what you're looking for?
0

I think that you will want an array of car objects. You can do this with a map like this:

let carList = result.map(car => {
 return {
        Constructeur,
        Modele,
        Couleur,
        Immat,
        VIN,
        DMC: car.Date_Mise_en_circulation,
        Enregistrement: car.Date_enregistrement
     }
})

or to follow your current coding pattern and use an arr.push()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.