【问题标题】:Map the cell to display JSON data in HTML table映射单元格以在 HTML 表格中显示 JSON 数据
【发布时间】:2015-10-29 05:24:52
【问题描述】:

我想通过映射第一行(动态 - 产品)和列(供应商)来显示单元格的 JSON 数据。这是 JSON 输入和代码:

$(document).ready(function () {
    var json = [{
        "Supplier": "Supplier1",
        "Product": "Oxygen",
        "Quantity": 50
    }, {
        "Supplier": "Supplier1",
        "Product": "Hydrogen",
        "Quantity": 100
    }, {
        "Supplier": "Supplier1",
        "Product": "Carbon",
        "Quantity": 50
    }, {
        "Supplier": "Supplier2",
        "Product": "Carbon",
        "Quantity": 200
    }, {
        "Supplier": "Supplier2",
        "Product": "Oxygen",
        "Quantity": 100
    }, {
        "Supplier": "Supplier3",
        "Product": "Hydrogen",
        "Quantity": 50
    }];
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $('<tr/>');
        tr.append("<td>" + json[i].Supplier + "</td>");
        tr.append("<td>" + json[i].Product + "</td>");
        tr.append("<td>" + json[i].Quantity + "</td>");
        $('table').append(tr);
    }
});

这是桌子:

我想重新排列数据来得到这个:

映射供应商和产品,显示数量。都是动态值。

请帮忙。 提前致谢。

【问题讨论】:

  • 是否可以更改收到的 JSON 以更好地匹配表格格式?
  • @RoryMcCrossan 应该是哪种格式?
  • 供应商数组,每个供应商都包含一系列产品。
  • @skubski 怎么绑定?

标签: javascript jquery html arrays json


【解决方案1】:

您可以使用 AJAX 根据您传递的参数返回 JSON。 这将允许您对其进行自定义。

另一种方法是采取: Supplier1 等并将它们添加到包含产品和数量的单独数组中。 然后遍历它们并根据产品在广告中出现的位置添加。

例如,我在供应商 2 上,我有产品 Carbon。检查头部是否出现碳。将 val 添加到行中的当前列。

function findAjax() {
                $.ajax({
                  type: "POST",
                  dataType: 'json',
                  url: '/Action/GetDynamicJson?format='$('#json-format').val(),
                  success: function(response){              
                        $('#table-container').html("");
                        $.each (response, function (index) {
                          if ($('#json-format').val() = '1'){
                            var tableRow = "";
                            tableRow = $('<tr/>');
                            tableRow.append("<td>" + response[index].Supplier + "</td>");
                            tableRow.append("<td>" + response[index].Product + "</td>");
                            tableRow.append("<td>" + response[index].Quantity + "</td>");
                            $('#table-container').append(tableRow);
                          }else{
                          }
                  });  
                  },
                  error: function(req, status, error) {
                      //console.log("findAjax "+ status+" "+error);
                  }
              });
};

【讨论】:

    【解决方案2】:

    对不起,我对jQuery不熟悉,所以我在某些地方使用了原生JavaScript。

    如果您无法从服务器端访问格式,您可以在客户端更改格式,如下所示:

    $(document).ready(function() {
        var json = [{
            "Supplier": "Supplier1",
            "Product": "Oxygen",
            "Quantity": 50
        }, {
            "Supplier": "Supplier1",
            "Product": "Hydrogen",
            "Quantity": 100
        }, {
            "Supplier": "Supplier1",
            "Product": "Carbon",
            "Quantity": 50
        }, {
            "Supplier": "Supplier2",
            "Product": "Carbon",
            "Quantity": 200
        }, {
            "Supplier": "Supplier2",
            "Product": "Oxygen",
            "Quantity": 100
        }, {
            "Supplier": "Supplier3",
            "Product": "Hydrogen",
            "Quantity": 50
        }];
    
        var data = {}; // reformat the data
        var products = []; // types of products
    
        json.forEach(function(entry) {
            if (!data.hasOwnProperty(entry.Supplier)) {
                data[entry.Supplier] = {};
            }
    
            if (data[entry.Supplier].hasOwnProperty(entry.Product)) {
                data[entry.Supplier][entry.Product] += entry.Quantity;
            } else {
                data[entry.Supplier][entry.Product] = entry.Quantity;
            }
    
            // add new product type
            if (products.indexOf(entry.Product) === -1) {
                products.push(entry.Product);
            }
        });
    
        // set <th> line
        $('table').append('<tr><th>Supplier</th><th>' +
            products.join('</th><th>') +
            '</th></tr>');
    
        var table_str = '';
    
        for (entry in data) {
            if (data.hasOwnProperty(entry)) {
                table_str += '<tr>';
                table_str += '<td>' + entry + '</td>';
                products.forEach(function(product) {
                    if (data[entry].hasOwnProperty(product)) {
                        table_str += '<td>' + data[entry][product] + '</td>';
                    } else {
                        table_str += '<td></td>';
                    }
                });
                table_str += '</tr>';
            }
        }
    
        $('table').append(table_str);
    
        console.log(data);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table></table>

    【讨论】:

    • 非常感谢 :) 这就是我要找的。​​span>
    【解决方案3】:

    您也可以使用简单的逻辑来做到这一点。

    您只需根据供应商对 json 进行排序。然后从 json 数据中获取所有可用的产品。

    剩下的事情都由逻辑来完成。

    这里正在工作 jsfiddle: http://jsfiddle.net/jdk2f7gr/

    javascript 代码

    $(document).ready(function () {
       var json = [{
            "Supplier": "Supplier1",
            "Product": "Oxygen",
            "Quantity": 50
        }, {
            "Supplier": "Supplier1",
            "Product": "Hydrogen",
            "Quantity": 100
        }, {
            "Supplier": "Supplier1",
            "Product": "Carbon",
            "Quantity": 50
        }, {
            "Supplier": "Supplier2",
            "Product": "Carbon",
            "Quantity": 200
        }, {
            "Supplier": "Supplier2",
            "Product": "Oxygen",
            "Quantity": 100
        }, {
            "Supplier": "Supplier3",
            "Product": "Hydrogen",
            "Quantity": 50
        },
        {
            "Supplier": "Supplier3",
            "Product": "Nitrogon",
            "Quantity": 200
        }];
    
        function sortResults(prop, asc) {
            json = json.sort(function(a, b) {
            if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
            else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
            });
    
        }
        sortResults('Supplier',true);
    
        var tr;
        var supName=json[0].Supplier;
        var productList=$.unique(json.map(function (d) {
        return d.Product;}));
    
        var prod={};
        function appendHeader(productList){
            tr = $('<tr/>');
            tr.append("<th>Supplier</th>");
            for(var i=0;i < productList.length; i++)
                {               
                        tr.append("<th>" + productList[i] + "</th>");           
                }
                $('table').append(tr);      
        }
        appendHeader(productList);
    
        function appendRow(supName,prod){
            tr = $('<tr/>');
                tr.append("<td>" + supName + "</td>");
                for(var i=0;i < productList.length; i++)
                {
                    if (prod[productList[i]]) {
                        tr.append("<td>" + prod[productList[i]] + "</td>");
                    } else {
                        tr.append("<td></td>");
                    }
    
                }
    
    
                $('table').append(tr);
        }
    
        for (var i = 0; i < json.length; i++) {
    
            if(supName===json[i].Supplier){
                if(prod[json[i].Product]){
                  prod[json[i].Product]= prod[json[i].Product] + json[i].Quantity;
                }else{
                     prod[json[i].Product]=json[i].Quantity;
                }
            }
            else
            {
                appendRow(supName,prod);
                prod={};
                supName=json[i].Supplier;
                 if(prod[json[i].Product]){
                  prod[json[i].Product]= prod[json[i].Product] + json[i].Quantity;
                }else{
                     prod[json[i].Product]=json[i].Quantity;
                }
            }
    
    
        }
        appendRow(supName,prod);
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-22
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      相关资源
      最近更新 更多