The problem is that you're pushing a reference to the same object on each iteration. In doing so, the index
property on the temp
object will be the value from the last iteration.
In addition, there are only two elements, and the for
loop was executed three times because of the condition i <= len
(it should have been i < len
). Due to this, the value was undefined
on the last iteration, because the element doesn't exist. This resulted in all the index
properties on the temp
property being set to undefined
.
If you want a native JS solution, you could simply use the following instead:
var elements = document.querySelectorAll('.aws');
var values = [];
for (var i = 0; i < elements.length; i++) {
values.push({index: elements[i].value});
}
In the snippet above, a new object is pushed to the values
array on each iteration (rather than a reference to the same object). The for
loop condition is also i < elements.length
(rather than i <= elements.length
), so it will only iterate 2 times (rather than 3 like in your example).
If you want a shorter jQuery solution, simply use the .map()
method:
var values = $('.aws').map(function () {
return {index: this.value };
}).get();