Hakkı
Hakkı

Reputation: 840

comparing two different array types in javascript or jquery

I have two different array types. One of them string array another object array;

stringArray = ["P1", "P2", "P3"];
objectArray = [{ P: "P1", PO: 5}, { P: "P3", PO: 10}];

I want to put object array to a table. String array elements must be table headers.

If object array has P == "P1" put 5 to cell. Else put empty cell to row.

I tried this but this put multiple empty cells.

This is my code "tKeys" = stringArray, "Ciktilar" = objectArray

var baslikEklendiMi = false;
var satirEkle = function(CalismaTipi, Ciktilar, tKeys)
{
    var satir = '<td>' + CalismaTipi + '</td>';
    $.each(tKeys, function (i, val) {
        if (baslikEklendiMi == false) {
            $("#tblBaslik").append("<th>" + val+ "</th>");
        }

        $.each(Ciktilar, function (j, obj) {
            if (val == obj.P) {
                satir += '<td><b>' + obj.PO+ '</b></td>';
            }
            else {
                satir += '<td></td>';
            }
        });
    });

    baslikEklendiMi = true;
    $("#tblListe").append('<tr>' + satir + '</tr>');
}

Upvotes: 4

Views: 121

Answers (3)

bloodyKnuckles
bloodyKnuckles

Reputation: 12079

To get something like:

|--|--|--|--|
|ct|P1|P2|P3|
|--|--|--|--|
|??|5 |  |10|
|--|--|--|--|

There are five changes that need to be made to your code:

1) Line 7 (below): Instantiate emptyCell, assign false;

2) Line 9: Add $("#tblBaslik").append("<th>ct</th>") to account for CalismaTipi column,

3) Line 25-27: Move satir += '<td></td>' to outside the Ciktilar loop.

4) Line 22: Assign true to emptyCell.

5) Line 18-19: Reset emptyCell and exit the Ciktilar loop.

var stringArray  = ["P1", "P2", "P3"];
var objectArray  = [{ P: "P1", PO: 5}, { P: "P3", PO: 10}];

var baslikEklendiMi = false;
var satirEkle = function(CalismaTipi, Ciktilar, tKeys)
{
    var emptyCell = false;                                // Line 7
    var satir = '<td>' + CalismaTipi + '</td>';
    $("#tblBaslik").append("<th>ct</th>");                // Line 9
    $.each(tKeys, function (i, val) {
        if (baslikEklendiMi === false) {
            $("#tblBaslik").append("<th>" + val+ "</th>");
        }

        $.each(Ciktilar, function (j, obj) {
            if (val == obj.P) {
                satir += '<td><b>' + obj.PO+ '</b></td>';
                emptyCell = false;                         // Line 18
                return false;
            }
            else {
              emptyCell = true;                            // Line 22
            }
        });
        if (emptyCell) {                                   // Line 24
            satir += '<td></td>';
        }
    });

    baslikEklendiMi = true;
    $("#tblListe").append('<tr>' + satir + '</tr>');
};
satirEkle('??', objectArray, stringArray);

The reason you need to move satir += '<td></td>'; outside the Ciktilar loop is because the stringArray list does not correspond directly to the objectArray list. You want to check ALL the stringArray elements to find a match, and if no match after ALL the stringArray elements are checked THEN write an empty cell. So, rather than write to satir in the loop, set an emptyCell flag, and check that flag after the loop.

JSBin example.

Upvotes: 1

Redu
Redu

Reputation: 26161

I would like to do with a tool that i use very often to generate table HTML from an array of object or objects. So the below code will generate a table for you. The generic tableMaker function takes an array of an object or an array of multiple objects provided in the first argument. All objects should have same keys (properties) since these keys are used to create the table header (if the second argument is set to true) and the values are used to create each row. It will return an HTML table text. You can see the tableMaker function working with a smaller size data at here. You can also practice it with some sample and simple data you may produce.

var tableMaker = (o,h) => {var keys = o.length && Object.keys(o[0]),
                           rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
                                                                                           : "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
                           rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
                           return rows.length ? "<table>" + rows + "</table>" : "";
                          },
   stringArray = ["P1", "P2", "P3"],
   objectArray = [{ P: "P1", PO: 5}, { P: "P3", PO: 10}],
   tableObject = stringArray.reduce((p,c) => {var fo = objectArray.find(f => f.P == c);
                                               p[c] = fo ? fo.PO : "";
                                               return p;} ,{}),
     tableHTML = tableMaker([tableObject],true);
document.write(tableHTML);
console.log(tableHTML);

Upvotes: 1

Mario Santini
Mario Santini

Reputation: 3003

You have to change your code like this:

var satirEkle = function(CalismaTipi, Ciktilar, tKeys) {
    var satir = '<td>' + CalismaTipi + '</td>';
    $.each(tKeys, function (i, val) {
        if (baslikEklendiMi == false) {
            $("#tblBaslik").append("<th>" + val+ "</th>");
        }
        var emptyCell = false;
        $.each(Ciktilar, function (j, obj) {
            if (val == obj.P) {
                satir += '<td><b>' + obj.PO+ '</b></td>';
            }
            else {
                emptyCell = true;
            }
        });

        if (emptyCell) {
            satir += '<td>-</td>';
        } 
    });

    baslikEklendiMi = true;
    $("#tblListe").append('<tr>' + satir + '</tr>');
}

You should add a char inside the empty cell to have a more friendly layout.

A good choose is the empty html space &nbsp;.

Hope this helps.

Upvotes: 1

Related Questions