I need to return an array of objects but my code only returns the last value of the fixes

1

Hello, I am programming a code that is returning the last value of each object that I store and what I want is for me to return all the objects in that array. Any correction?

var names = ["messi","west","tom","harry"];
var types = ["perro","gato","paloma","cuy"];
var breeds = ["chiguagua","rallado","raviche","montero"];

function createAnimalObjects(names, types, breeds) {

var animal = new Animal(names, types, breeds);
var animalsArray = [];
var arrayReference = names;
for (var i = 0; i < arrayReference.length; i++) {
    animal.name = names[i];
    animal.type = types[i];
    animal.breed = breeds[i];

    animalsArray.push(animal);
}
return animalsArray;
}
createAnimalObjects(names, types, breeds);
// for test 
function Animal (name, type, breed) {
this.name = name;
 this.type = type;
 this.breed = breed;
}
    
asked by user3821102 20.12.2017 в 21:42
source

1 answer

1

When you make the push() for animalsArray at that time, create the new animal:

var names = ["messi","west","tom","harry"];
var types = ["perro","gato","paloma","cuy"];
var breeds = ["chiguagua","rallado","raviche","montero"];

function createAnimalObjects(names, types, breeds) {

   var animal = new Animal(names, types, breeds);
   var animalsArray = [];
   var arrayReference = names;
   for (var i = 0; i < arrayReference.length; i++) {
      animalsArray.push(new Animal(names[i],types[i],breeds[i]));
      //así ahorras código y evitas el error que te esta dando
    }
  return animalsArray;
  }
 createAnimalObjects(names, types, breeds);
// for test 
function Animal (name, type, breed) {
    this.name = name;
    this.type = type;
    this.breed = breed;
 }
    
answered by 20.12.2017 / 21:51
source