Object not working correctly when read from an array

New to objects so I’m not doubt doing some completely wrong. Am building an object which I then push into an array for later retrieval.


	// Okay using an object and an array to store the data here.
	customer.name = name;
	customer.plantype = planType;
	customer.numtexts = numTexts;
	
	transArray.push(customer);

The above code is in a do … while, which hopefully is building up the transArray.

Later in the program I attempt to extract the same object for reporting, if wondering this is for a college assignment. Please note not asking anyone to write the entire script, have most of it working.


for(var i=0; i < transArray.length ; i++) {
	customer = transArray[i];
	alert("Customer " + customer.name);

My problem is the customer object always contains the last values for the customer object, i.e doesn’t appear to overwrite customer from the array ???

Hi,

Before your for loop, what does console.log (transArray); output?

i.e.

console.log (transArray);
for(var i=0; i < transArray.length ; i++) {
	customer = transArray[i];
	alert("Customer " + customer.name);
}

Thanks for the suggestion.

Put an alert prior to loading the customer object and the values are correctly changing, however the console log indicates the array contains the correct number of objects but each object is somehow the final data entered

So for example if I enter the names Sue, Kevin, Paul

the customer.name property is always Paul for the three objects in the array.

Ah got it, with a little help from flatmate

I needed to declare the object as new on each iteration :slight_smile:


	// Okay using an object and an array to store the data here.
var customer = new custObject();	
	customer.name = name;
	customer.plantype = planType;
	customer.numtext = numTexts;
	
	transArray.push(customer);

Can you post the code you are using to build the array?

Edit:

You were quicker :slight_smile: