I've been working with AngularJS and integrated JQuery library in my project.
I am using JQuery's $.each()
function to loop through my class.
I want to create an array of objects out of it just like the format below:
[
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
{"invoice_no":"value1", "brand":"value2", "model":"value3"},
]
HTML
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
<div class="panels">
<input class="form-control" name="invoice_no">
<input class="form-control" name="brand">
<input class="form-control" name="model">
</div>
JS Controller
$scope.saveData = function(){
var arrayOFProducts = [];
var object = {};
angular.element('.panels').each(function(){
$(this).find('.form-control').each(function(){
var key = $(this).attr('name');
var value = $(this).val();
object [key] = value;
});
arrayOFProducts.push(object);
});
console.log(arrayOFProducts);
}
The main problem here is that I get the same values for all the json objects inside the array. It seems that only the last input values are being created as an object and the it pushes it to the array 5 times..
The issue is because you need to reset the object you append back to an empty state after each iteration of the outer loop. Try this:
$scope.saveData = function() {
var arrayOFProducts = [];
angular.element('.panels').each(function() {
var obj = {}; // note this moved to here
$(this).find('.form-control').each(function() {
var key = $(this).attr('name');
var value = this.value;
obj[key] = value;
});
arrayOFProducts.push(object);
});
console.log(arrayOFProducts);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With