简体   繁体   中英

Map the cell to display JSON data in HTML table

I want to display the JSON data of the cell by mapping the first row (dynamic - products) and column (Suppliers). This is the JSON input and the code:

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

This is the table:

在此处输入图片说明

I want to rearrange the data to get this:

在此处输入图片说明

Map supplier and product, display the quantity. All are dynamic values.

Please Help. Thanks in Advance.

you can do this using simple logic as well.

you need to just sort your json based on supplier. then get all available product from json data.

and logic will be do rest of the thing.

here is working jsfiddle: http://jsfiddle.net/jdk2f7gr/

javascript code

$(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);

});

You could just use AJAX to return JSON based on the parameter you pass through. This will allow you to customise it.

The other way would be to take the: Supplier1 etc and add them to a seperate array that would contain Product and Quantity. Then itterate through them and add based on the position in thead that the Product appear.

Such as, I am on supplier2, I have product Carbon. Check thead for position Carbon appeaers. Add val to current col in row.

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

Sorry, I'm not familiar with jQuery, so I use the native JavaScript in some places.

If you can't access to the format from the server side, you may change your format on client side, like below:

 $(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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM