0

I think this is fairly straightforward but I am not sure. I am trying to insert copies of an object into an array, changing the value of some of them. Ideally I would like to do this without a constructor function. Here is what I have:

var person = {
  gender: 'Male',
  age: 50
}

var people = [];

for (var i = 0; i < 5; i++) {
  var favoriteWord = "hi";
  person.favoriteWord = favoriteWord;
  people.push(person);
}

for (var i = 0; i < 5; i++) {
  var favoriteWord = "goodbye";
  person.favoriteWord = favoriteWord;
  people.push(person);
}

console.log(people)

What happens is that every item in the array takes on the same favoriteWord property. In essence all of the items in the array are the same.

Is there a way to change this or do I have to use a function?

Startec
  • 12,496
  • 23
  • 93
  • 160
  • It is always the same object. You'd have to create a blank object, and copy all the properties over. – elclanrs Feb 23 '15 at 08:32
  • I see. This was to help me rapidly put small variations of products into a database. Would you use your method to achieve that? – Startec Feb 23 '15 at 08:33

0 Answers0