Reputation: 689
I'm am iterating over dynamically generated div which contains a table. While I'm iterating over rows, Suppose I'm having two rows, I'm getting two results. But the problem is that both the results contain values of last row of table. Here is my code:
$(this)
.children('.js-charge-data')
.children('.js-charging-line-wrapper')
.find('.js-chargeline-tbody')
.children('tr')
.each(function() {
chargingLineJSON['chargingType'] = 'IoT';
chargingLineJSON['chargeCategoryName'] = $(this).find('.js-charging-category').val().trim();
chargingLineJSON['subCategoryName'] = $(this).find('.js-charging-sub-category').val().trim();
chargingLineJSON['backEndProductName'] = $(this).find('.js-charging-sub-category').children(':selected').data('backend_product_name');
chargingLineJSON['shipToAddressId'] = '123';
chargingLineJSON['chargePerUnit'] = $(this).find('.js-unit-charge').val().trim();
chargeLineListJSON['chargingLine'] = chargingLineJSON;
chargingLineJSONArray.push(chargeLineListJSON);
});
Please let me know what mistake am I doing?
Upvotes: 0
Views: 84
Reputation: 24915
As commented and credited in @Satpal's answer, issue is due to object copied as a reference.
Not repeating the comment in my answer though to reduce duplication of data.
You can use something like this.
$(this)
.find('.js-charge-data .js-charging-line-wrapper .js-chargeline-tbody tr')
.each(function() {
let category = $(this).find('.js-charging-category');
let subCategory = $(this).find('.js-charging-sub-category');
let selectedSubCategory = $(this).find('.js-charging-sub-category :selected');
let unitCharge = $(this).find('.js-unit-charge');
chargingLineJSONArray.push({
chargingType: 'IoT',
shipToAddressId: '123'
chargeCategoryName: category.val().trim(),
subCategoryName: subCategory.val().trim(),
backEndProductName: selectedSubCategory.data('backend_product_name'),
chargePerUnit: unitCharge.val().trim()
});
// Not sure what this line is about?
// You are saving reference to self in a property.
// chargeLineListJSON['chargingLine'] = chargingLineJSON;
});
Note: I have not tested code as mark is missing.
Upvotes: 1
Reputation: 133403
You are pushing same object chargingLineJSON
to the array, Create a new object in the .each()
block
.each(function () {
//Create a new object
var chargingLineJSON = {};
//Your code
chargingLineJSONArray.push(chargeLineListJSON);
});
As per @Rajesh comment
Objects are copied using reference. So in second iteration, when you set value to object's property, you are overriding value at a memory location and not in a locat variable. Hence, same values
Upvotes: 2