Jonathan
Jonathan

Reputation: 2880

Format result after looping object

I'm looping an object and expect the result as elements of a table

var db = {
    "id": "8",
    "user_id": "24",
    "batchno": "367727",
    "ht_number": "jibhbu",
    "ht_taste": "uvyutvc",
    "pp_flavour": "ytv,yurtcrc,urt",
    "pp_fruit_batch": "cuyt,cytc,yt",
    "sl_flavour": "ouihyuigytvytc",
    "sl_appearance": "rtctr"
  },
  pp_ = '<table><tbody>';
for (var i in db) {
  if (db.hasOwnProperty(i)) {
    var js = db[i].split(',');
    for (var x in js) {
      if (i.startsWith('pp_')) {
        pp_ += '<tr><td>' + i + ' ' + x + ' : ' + js[x] + '</td></tr>';
      }
    }
  }
}
pp_ += '</tbody></table>';
document.write(pp_);
I am splitting values that have commas so that each index of an array sits on 1 row (tr)

what I can't figure out is how to place elements with the same index on the same level (row) so I can I have something like

table, td {
border: 1px solid black;
}
<table>
    <tbody>
        <tr>
            <td> pp_flavour 0 - its value </td>
            <td> pp_fruit_batch 0 - its value </td>
        </tr>
        <tr>
            <td> pp_flavour 1 - its value </td>
            <td> pp_fruit_batch 1 - its value </td>
        </tr>
        <tr>
            <td> pp_flavour 2 - its value </td>
            <td> pp_fruit_batch 2 - its value </td>
        </tr>
    </tbody>
</table>

<br>

<table>
    <tbody>
        <tr>
            <td> sl_favour 0 - its value </td>
            <td> sl_appearance 0 - its value </td>
        </tr>
        <tr>
            <td> sl_favour 1 - its value </td>
            <td> sl_appearance 1 - its value </td>
        </tr>
    </tbody>
</table>

and so on...

Upvotes: 0

Views: 81

Answers (4)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Create a loop, incrementing a counter, which will determine if a key's split value should be output.

If there are no more values found at the index of the counter, stop looping.

var db = {
    "id": "8",
    "user_id": "24",
    "batchno": "367727",
    "ht_number": "jibhbu",
    "ht_taste": "uvyutvc",
    "pp_flavour": "ytv,yurtcrc,urt",
    "pp_fruit_batch": "cuyt,cytc,yt",
    "sl_flavour": "ouihyuigytvytc",
    "sl_appearance": "rtctr"
  },
  s = '';

['pp_', 'ht_', 'sl_'].forEach(function(type) {
  var i,
      found = true;
  
  s += '<table>';
  
  for(i = 0 ; found ; i++) {
    s += '<tr>';
    found = false;
    Object.keys(db).forEach(function(key) {
      var js = db[key].split(',');
    
      if(js[i] && key.startsWith(type)) {
        found = true;
        s += '<td>' + key + ' ' + i + ' : ' + js[i] + '</td>';
      }
    });
    s += '</tr>';
  }
  s += '</table>';
});

document.write(s);
td {
  border-bottom: 1px solid #bbb;
  border-right: 1px solid #ddd;
  padding: 0.5em;
}

table {
  border: 1px solid black;
  margin-bottom: 1em;
  border-spacing: 0;
}

Upvotes: 1

Nemani
Nemani

Reputation: 784

You can try adding each value of the table to a 2-D array and than form the table from this 2-D array

try below solution

NOTE: this will also work with different number of rows and Column.

var db = {
    "id": "8",
    "user_id": "24",
    "batchno": "367727",
    "ht_number": "jibhbu",
    "ht_taste": "uvyutvc",
    "pp_flavour": "ytv,yurtcrc,urt",
    "pp_fruit_batch": "cuyt,cytc,yt",
    "sl_flavour": "ouihyuigytvytc",
    "sl_appearance": "rtctr"
  };
function createTable(myKey){
var  rows = [];
for (var dbKey in db) {
  if (db.hasOwnProperty(dbKey)) {
    if (dbKey.startsWith(myKey)) {
      var values = db[dbKey].split(',');
      for (var val in values) {
        if (!rows[val])
          rows[val] = [];
        rows[val].push('<td>' + dbKey + ' ' + val + ' : ' + values[val] + '</td>');
      }
    }
  }
}

var myTable = '<table><tbody>';
for (var i = 0; i < rows.length; i++) {
  myTable += "<tr>" + rows[i].join("") + "</tr>";
}
myTable += '</tbody></table>';
return myTable;
}
var ht_table = createTable("ht_");
document.getElementById("myTable").innerHTML +="<br/>"+ ht_table;

var pp_table = createTable("pp_");
document.getElementById("myTable").innerHTML +="<br/>"+ pp_table;

var sl_table = createTable("sl_");
document.getElementById("myTable").innerHTML += "<br/>"+ sl_table;
table, td {
  border-style: solid;
}
<p id="myTable">

</p>

Upvotes: 1

Greg Depoire-Ferrer
Greg Depoire-Ferrer

Reputation: 192

You could try indexing the database like this:

var db = {
  "id": "8",
  "user_id": "24",
  "batchno": "367727",
  "ht_number": "jibhbu",
  "ht_taste": "uvyutvc",
  "pp_flavour": "ytv,yurtcrc,urt",
  "pp_fruit_batch": "cuyt,cytc,yt",
  "sl_flavour": "ouihyuigytvytc",
  "sl_appearance": "rtctr"
};

var prefixes = ["pp", "ht", "sl"];
var prefixedDb = {};
var result = "";

for (var i in db) {
  if (db.hasOwnProperty(i)) {
    var parts = i.split("_");
    var prefix = parts[0];

    if (prefixes.indexOf(prefix) === -1) continue;
    if (prefixedDb[prefix] === undefined) {
      prefixedDb[prefix] = {};
    }

    prefixedDb[prefix][parts.slice(1).join("_")] = db[i];
  }
}

for (var k in prefixedDb) {
  if (prefixedDb.hasOwnProperty(k)) {
    var db = prefixedDb[k];
    var dbIndexed = {};

    for (var i in db) {
      if (db.hasOwnProperty(i)) {
        var vals = db[i].split(',');

        vals.forEach(function(val, j) {
          if (dbIndexed[j] === undefined) {
            dbIndexed[j] = {};
          }

          dbIndexed[j][i] = val;
        });
      }
    }

    result += "<table><tbody>";

    for (var i in dbIndexed) {
      if (dbIndexed.hasOwnProperty(i)) {
        result += "<tr>";

        var indexVals = dbIndexed[i];
        for (var j in indexVals) {
          if (indexVals.hasOwnProperty(j)) {
            result += "<td>" + j + " " + i + " - " + indexVals[j] + "</td>";
          }
        }

        result += "</tr>";
      }
    }

    result += "</tbody></table>";
  }
}

document.write(result);
table, td {
  border: 1px solid black;
}

Please note that this code may not be the most optimized code for this task.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386570

You could take the wanted values out of the object, split them and take the max length for iterating the rows for the table. Then assemble the table by iterating the values.

var db = { pp_flavour: "ytv,yurtcrc,urt", pp_fruit_batch: "cuyt,cytc,yt,42" },
    values = Object.keys(db).filter(k => k.startsWith('pp_')).map(k => (db[k] || '').split(',')),
    length = values.reduce((r, a) => Math.max(r, a.length), 0),
    table = document.createElement('table'),
    tr,
    i;

for (i = 0; i < length; i++) {
    tr = document.createElement('tr');
    table.appendChild(tr);
    values.forEach(function (a) {
        var td = document.createElement('td');
        td.appendChild(document.createTextNode(i in a ? a[i] : ''));
        tr.appendChild(td);
    });
}

document.body.appendChild(table);

Upvotes: 1

Related Questions