JavaScript 如何在for循环中使用forEach函数

JavaScript 如何在for循环中使用forEach函数

问题描述

我已经创建了一个价格列表,并希望根据每个sku值,在每个产品下方一起显示价格。

我有一个数据数组,通过循环遍历并将其推送到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>

我想我需要使用for each函数…我尝试在for循环内部使用了一个jquery的foreach函数,但最终得到了奇怪的结果。

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/

解决方案

首先使用groupedData按照SKU进行分组,然后遍历arr数组并添加每个产品。

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);
            }
        }

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程