I have a function with a loop that save data in an object, the foreach loop is saving the last value
var n = new Array();
var weight = new Array();
var obj = {};
var as = [];
// var temp;
$("input:checked").each(function(){
temp = this.value;
// n.push(this.value);
obj['ids'] = temp;
obj['weight']= $("#weight"+temp).val();
as.push(obj);
delete temp;
});
console.log(as);
the result of console.log is
(5) [{…}, {…}, {…}, {…}, {…}]
0: {ids: "298", weight: "1.00"}
1: {ids: "298", weight: "1.00"}
2: {ids: "298", weight: "1.00"}
3: {ids: "298", weight: "1.00"}
4: {ids: "298", weight: "1.00"}
this should be
(5) [{…}, {…}, {…}, {…}, {…}]
0: {ids: "on", weight: "undefined"}
1: {ids: "4", weight: "1"}
2: {ids: "5", weight: "2"}
3: {ids: "6", weight: "3"}
4: {ids: "298", weight: "4"}
You're adding the same reference to the object in every push()
call. Create a new object in every iteration by moving var obj = {};
inside the loop. Also, if you define temp
within the loop you don't need to use delete temp
- not that it's of any use in this instance anyway.
var n = [], weight = [], as = [];
$("input:checked").each(function() {
var temp = this.value;
var obj = {};
obj['ids'] = temp;
obj['weight'] = $("#weight" + temp).val();
as.push(obj);
});
console.log(as);
That being said, you can improve the logic by using map()
instead:
let as = $("input:checked").map(function() {
let temp = this.value;
return {
ids: temp,
weight: $("#weight" + temp).val()
}
}).get();
console.log(as);