I have a JS object like this:
{
promo_name: "value",
discount_type: "value",
discount: "value",
products: [
{ id: 1, name: 'name'},
{ id: 2, name: 'name'},
]
}
My objective is to display the results in a view. My problem is that I do not know how to iterate over an array inside an object.
The data is coming from an Ajax request and then parsed into a JS object.
I am using jQuery $.each to iterate over the res object and display property values like this:
$.each(res, function (key, value) {
$("#coupon_data").show();
$("#coupon_details").html(
'<div class="alert alert-success">' +
'<h4>Promotion Details</h4>' +
'<hr>' +
'<p>Promotion: ' + res.promo_name + '</p>' +
'<p>Discount type: ' + res.discount_type + '</p>' +
'<p>Amount: ' + res.discount + '%</p>' +
'</div>'
);
});
The three properties (res.promo_name, res.discount_type, res.discount) display, but because the array length varies I cannot display its values like this:
res.products[0].name
res.products[1].name
I believe that I need to loop over the array that's inside the object and display the number of elements it might contain. This is where I am stuck.
$.each(res.products, function(index, val) { ....... }res.products.length