I am pushing elements into array, and the problem is that each time I push a new element, all the previous elements become equal to the last one. I have come across this post, but I still can't see how to fix the issue
Please see this jsFiddle. As the post suggests, I moved the declaration of instance
to the for-loop, but I've still got the same problem. Namely, the output of the code looks like this: [46, 46]
. However, I would expect it to be [23, 46]
.
I am really going crazy. Any ideas???
$(document).ready(function() {
var json = {'name': 'Anna', 'counter': 1}
var counters = [23, 46];
var result = [];
$(counters).each(function() {
var instance = json;
instance.counter = this;
result.push(instance);
});
$(result).each(function(){
$('#test').append('<li>' + this.counter + '</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id = 'test'>
</ul>