John
John

Reputation: 17

Pushing Objects Into Array

I am trying to push objects into an array using an each loop, while the amount of objects is right in the end the data in the object is repeated with the last entry.

When I log the object inside the loop it is giving me two sets of data, the first one is correct, the second one is the last set of data for the loop.

I have tried logging the data to the console but it is giving me really weird values.

$.getJSON(url, function(data) {

  var entry = data.feed.entry;


     var nietos = [];
     var obj = {};



  $(entry).each(function(){

   var title = String(this.gsx$title.$t); 
   var lastName = String(this.gsx$lastname.$t);  
   var firstName = String(this.gsx$firstname.$t);        
   var email = String(this.gsx$email.$t);
   var department = String(this.gsx$department.$t);      

      console.log(lastName);


      obj["title"] = title;
      obj["lastName"] = lastName;
      obj["firstName"] = firstName;
      obj["email"] = lastName;
      obj["department"] = department;

      //console.log(obj);
      /*
      (index):345 {title: "Cook II", lastName: "Woon", firstName: "Ra", email: "Wson", 
      department: "LR"}department: "WL Span"email: "Zuniga"firsame: "Lea"lastName: "Zga"title: "Regular Teer"__proto__: Object*/


      //nietos.push(obj);

});

//console.log(nietos);

//97: {title: "Regular Teacher", lastName: "Zga", firstName: "Leticia", email: "Zuga", department: "WL S"}

});

Expected:

{title: "Teacher", lastName: "Teacher1", firstName: "Teachername", email: "[email protected]",},
{title: "Teacher2", lastName: "Teacher2", firstName: "Teachername2", email: "[email protected]",},,
{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "[email protected]",},  

Actual output:

{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "[email protected]",},  
{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "[email protected]",},  
{title: "Teacher3", lastName: "Teacher3", firstName: "Teachername3", email: "[email protected]",},

Upvotes: 0

Views: 81

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

You create just one object with var obj = {};, then you modify that one object in the "loop" and add references to that object to the array.

Create a new var obj = {} inside of each loop iteration (inside the .each callback).

As a sidenote, let profesor = {}; would be much better ...

Upvotes: 1

Related Questions