Reputation: 13
I have a single input row that needs to be expanded to create multiple rows, with 6 fields being repeated on each row, and one unique field added to each row. The unique fields are stored in arrparentjobs array, and I know that they have unique values.
When the code runs, the resulting rows all contain the exact same data, which happens to be the values of the last items being pushed.
What am I doing wrong here?
Thanks much, Joe
var dataRowsOutput = [];
arrVolDataOutput.playerid = volDataRow.playerId;
arrVolDataOutput.timestamp = volDataRow.timestamp;
arrVolDataOutput.playername = volDataRow.playerName;
arrVolDataOutput.parentname = volDataRow.parent1Name;
arrVolDataOutput.parentphone = volDataRow.parent1Phone;
arrVolDataOutput.parentemail = volDataRow.parent1Email;
for (var j = 0; j < arrparentjobs.length; ++j) {
arrVolDataOutput.parentjob = arrparentjobs[j];
dataRowsOutput.push(arrVolDataOutput);
continue;
}
Upvotes: 1
Views: 3360
Reputation: 434665
the resulting rows all contain the exact same data
Yes they do and they do because push
pushes a reference – not a deep or even shallow copy – onto the array and you're simply changing the parentjob
while pushing the exact same arrVolDataOutput
object onto the array over and over again.
You need to create a new object on each iteration, something like this:
var dataRowsOutput = [];
for (var j = 0; j < arrparentjobs.length; ++j) {
dataRowsOutput.push({
parentjob: arrparentjobs[j],
playerid: volDataRow.playerId,
timestamp: volDataRow.timestamp,
playername: volDataRow.playerName,
parentname: volDataRow.parent1Name,
parentphone: volDataRow.parent1Phone,
parentemail: volDataRow.parent1Email
});
}
If there are other fields in your arrVolDataOutput
then you'll need to include those in the object literal as well.
Upvotes: 6