Push Object in Array [duplicate]

You’re pushing the same object into the array repeatedly, and just updating the id property on that object as you go.

If you want multiple objects in the array, you’ll need to create multiple objects:

var copyArray = [];
while (copyArray.length < 3) {
  copyArray.push({
    id: copyArray.length
  });
}
snippet.log(JSON.stringify(copyArray));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Leave a Comment