Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array push behavior

Although I have some basic JavaScript background, I stumbled upon this code that I wrote:

var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"[email protected]","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"[email protected]","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"[email protected]","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"[email protected]","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 final loop, I expected table to contain the arrays for Tom, Pat, and Sam . Instead, this is what I got:

table[["Tom","Moody","[email protected]",30]]
table[["Pat","Smith","[email protected]",32],["Pat","Smith","[email protected]",32]]
table[["Sam","Dawn","[email protected]",28],["Sam","Dawn","[email protected]",28],["Sam","Dawn","[email protected]",28]]
table[["Sam","Dawn","[email protected]",28],["Sam","Dawn","[email protected]",28],["Sam","Dawn","[email protected]",28],["Sam","Dawn","[email protected]",28]]

Why is push() replacing the previous entry in table? Any help will be highly appreciated.

like image 691
user2693135 Avatar asked Jan 06 '23 12:01

user2693135


2 Answers

The others already pointed out problems in your code.

However, you also make things more complicated than necessary. You can just do this:

var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"[email protected]","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"[email protected]","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"[email protected]","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"[email protected]","age":28}];

var table = data.map(function(user) {
    return [
      user.fName,
      user.lName,
      user.email,
      user.age,
    ];
});
      
console.log(table);

Or if you use ES6:

var table = data.map(user => [ user.fName, user.lName, user.email, user.age ];
like image 182
str Avatar answered Jan 08 '23 01:01

str


You don't need to write all the boilerplate code by hand. Use a proper array iterator (map in your case).

var table = data.map(function(user) {
   return [user.fName, user.lName, user.email, user.age];
});
like image 20
Yury Tarabanko Avatar answered Jan 08 '23 03:01

Yury Tarabanko