Although I have a basic JavaScript background, I came across this code that I wrote:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom@example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat@example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam@example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam@example.com","age":28}]
var tempArr=[];
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
In the last loop, I expected the table to contain arrays for Tom, Pat, and Sam. Instead, I got:
table[["Tom","Moody","Tom@example.com",30]]
table[["Pat","Smith","pat@example.com",32],["Pat","Smith","pat@example.com",32]]
table[["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28]]
table[["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28],["Sam","Dawn","sam@example.com",28]]
Why does push () replace the previous record in the table? Any help would be greatly appreciated.