Reputation:
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].*
Upvotes: 0
Views: 1715
Reputation: 114
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;
})
}
Upvotes: 0
Reputation: 84912
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;
}
Upvotes: 4