Problem:
I have created a price list and would like to display the prices together underneath each product based on each sku value.
I have an array of data which is looped through and then pushed into the div.
var arr = [
{
"sku": "552",
"title": "orange",
"price": "1.55",
"per": 1
},
{
"sku": "552",
"title": "orange",
"price": "2.00",
"per": 2
},
{
"sku": "552",
"title": "orange",
"price": "3.50",
"per": 4
},
{
"sku": "551",
"title": "bannana",
"price": "0.95",
"per": 1
},
{
"sku": "551",
"title": "bannana",
"price": "2.20",
"per": 3
},
{
"sku": "544",
"title": "apple",
"price": "0.70",
"per": 1
},
{
"sku": "501",
"title": "pear",
"price": "1.15",
"per": 1
}
];
for(var i=0; i<arr.length; i++){
var sku = arr[i].sku;
var title = arr[i].title;
var price = arr[i].price;
var per = arr[i].per;
var html = "<p>" + sku + " - " + title + "</p>";
html += "<p><b>" + per + "</b> - " + price + "</p>";
$("#div_1").append(html);
}
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<div id="div_1"></div>
I think I need to use the for each function…I have tried used a jquery foreach function inside the for loop but ended up with strange results.
for(var i=0; i<arr.length; i++){
var sku = arr[i].sku;
var title = arr[i].title;
var price = arr[i].price;
var per = arr[i].per;
var html = "<p>" + sku + " - " + title + "</p>";
$.each(arr, function(key, value) {
html += "<p><b>" + per + "</b> - " + price + "</p>";
});
$("#div_1").append(html);
}
https://jsfiddle.net/amxkwgy9/
Solution:
first group by SKU using groupedData then,iterate the arr array and add each product.
https://jsfiddle.net/grsn27hk/
var groupedData = {};
// Group the data by SKU
for (var i = 0; i < arr.length; i++) {
var sku = arr[i].sku;
if (!groupedData[sku]) {
groupedData[sku] = [];
}
groupedData[sku].push(arr[i]);
}
// Display the grouped data
for (var sku in groupedData) {
if (groupedData.hasOwnProperty(sku)) {
var products = groupedData[sku];
var skuTitle = products[0].sku + " - " + products[0].title;
var html = "<p>" + skuTitle + "</p>";
for (var j = 0; j < products.length; j++) {
var product = products[j];
html += "<p><b>" + product.per + "</b> - " + product.price + "</p>";
}
$("#div_1").append(html);
}
}